0
I started the studies with angular4.
I made a simple request that returns me one json
.
So far so good...
When making the comparison in my component
with the data returned from my service
, it also presents me an error in the console:
Script to component
where it causes error:
import { Component, OnInit } from '@angular/core';
//importando o serviço
import { CredentialsService } from './services/credentials.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(public cred: CredentialsService) {}
verifyUser(user, pw){
let dados;
this.cred.getCredentials().subscribe(res =>{
dados = res;
});
//o if fora do subscribe gera erro...
if(user == dados.credentials.user && pw == dados.credentials.password){
console.log('usuário logado');
}else{
console.log('usuário e senha errados');
}
}
ngOnInit() {
}
}
ERROR Typeerror: Cannot read Property 'credentials' of Undefined
But when I put the comparison(if) inside the subscribe
, the code works...
Pq this problem occurs?
"Functional code":
import { Component, OnInit } from '@angular/core';
//importando o serviço
import { CredentialsService } from './services/credentials.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(public cred: CredentialsService) {}
verifyUser(user, pw){
let dados;
this.cred.getCredentials().subscribe(res =>{
dados = res;
if(user == dados.credentials.user && pw == dados.credentials.password){
console.log('usuário logado');
}else{
console.log('usuário e senha errados');
}
});
}
ngOnInit() {
}
}