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

前端 未结 3 543
无人共我
无人共我 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:13

    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
            });
    }
    

提交回复
热议问题