Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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 { DataService } from '../../shared/data.service';

@Component({
  selector: 'topbar',
  templateUrl: './src/app/components/topbar/topbar.component.html',
  styleUrls: ['./src/app/components/topbar/topbar.component.css'],
  providers: [DataService]
})

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    
  }
}
like image 451
Lee Avatar asked Sep 15 '16 03:09

Lee


People also ask

What does subscribe () do in Angular?

Subscribe() is a method in Angular that connects the observer to observable events. Whenever any change is made in these observable, a code is executed and observes the results or changes using the subscribe method.

What to use instead of subscribe in Angular?

map instead of . subscribe. Later is mainly used if you want the response updated to the DOM.

When we use subscribe in Angular?

Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.


2 Answers

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    
  }
like image 98
Günter Zöchbauer Avatar answered Oct 24 '22 00:10

Günter Zöchbauer


component context "this" is not available inside of the subscribe(), to fix this, declare _this and assign this before the subscribe() as shown below;

    constructor (private dataService: DataService){
           const _this = this;
           dataService.getCompaniesCount().subscribe(res => {
              this.companyCount = res.count; // does't work
           });
           dataService.getCompaniesCount().subscribe(res => { _this.companyCount = res.count; //works
        });
}
like image 38
Naresh Chennuri Avatar answered Oct 23 '22 22:10

Naresh Chennuri