I started studies with angular4.
I made a simple request that returns me a json
.
So good!
When comparing in my component
with the data returned from my service
, it gives me an error in the console:
Script to component
where it generates 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: Can not read property 'credentials' of undefined
But when I put the comparison (if) inside subscribe
, the code works ...
Why does this problem occur?
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() {
}
}