Can't assign value to variable using subscribe() method in Angular 2

前端 未结 3 538
无人共我
无人共我 2021-02-12 13:58

The promise returns a value but I don\'t seem to be assigning the value properly in the subscribe method.

import { Component } from \'@angular/core\';
import {          


        
3条回答
  •  孤城傲影
    2021-02-12 14:27

    With this code

    export class TopbarComponent {
      companyCount;
    
      constructor (private dataService: DataService){
        dataService.getCompaniesCount().subscribe(res => this.companyCount = res.count); //doesn't work
        dataService.getCompaniesCount().subscribe(res => console.log(res.count)); //works    
      }
    }
    

    res => this.companyCount = res.count doesn't get executed immediately. When getCompaniesCount() makes a request to a server, it takes a long time until the response arrives and the observable calls the function passed to subscribe(...) (res => this.companyCount = res.count).

    The execution of the constructor, ngOnInit, ngAfterViewInit() and lots of other stuff will have happened before the response arrives.

    You can see

    subscribe(res => this.companyCount = res.count)
    

    like registering an event handler that gets called when an event happens.

    All code that depends on the data being available needs to be properly chained.

    The simplest way is to move to code into subscribe(...)

      constructor (private dataService: DataService){
        dataService.getCompaniesCount().subscribe(res => {
          this.companyCount = res.count); 
          // more code that depends on `res.count` being set goes here
        });
        dataService.getCompaniesCount().subscribe(res => console.log(res.count)); //works    
      }
    

提交回复
热议问题