Delay in return subscribe - Angular4

0

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() {

  }

}
    
asked by anonymous 17.10.2017 / 00:50

1 answer

0

Why when you put the if outside the subscribe function, it was executed before the return of your promise. And so the credentials property of your response was undefined :

  

ERROR TypeError: Can not read property 'credentials' of undefined.

Already when you put it inside the subscribe function, if only it was executed when the promise returned, in which case there was value in dados.credentials.user .

    
28.10.2017 / 03:35