Slow return subscribe - Angular4

Asked

Viewed 121 times

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

  }

}

1 answer

0

Because when you put if out of the subscribe function, it was executed before the return of your Password. And therefore, the property credentials of your sponse era Undefined:

ERROR Typeerror: Cannot read Property 'credentials' of Undefined.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.