本文介绍了无法使用Angular 2中的subscribe()方法为变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

promise返回一个值,但是我似乎没有在subscription方法中正确分配该值.

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

推荐答案

使用此代码

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不会立即执行.当getCompaniesCount()向服务器发出请求时,将花费很长的时间,直到响应到达并且Observable调用传递给subscribe(...)(res => this.companyCount = res.count)的函数.

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).

在响应到达之前,已经发生了构造函数ngOnInitngAfterViewInit()的执行.

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

你可以看到

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.

最简单的方法是将代码移入subscribe(...)

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
  }

这篇关于无法使用Angular 2中的subscribe()方法为变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:09