无法使用Angular 2中的subscribe()方法为变量赋值

Lee*_*Lee 16 angular

promise返回一个值,但我似乎没有在subscribe方法中正确赋值.

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    
  }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 13

有了这段代码

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    
  }
}
Run Code Online (Sandbox Code Playgroud)

res => this.companyCount = res.count没有立即执行.当getCompaniesCount()向服务器发出请求时,响应到达并且observable调用传递给()的函数需要很长时间.subscribe(...)res => this.companyCount = res.count

在响应到来之前ngOnInit,构造函数ngAfterViewInit()和许多其他东西的执行都会发生.

你可以看到

subscribe(res => this.companyCount = res.count)
Run Code Online (Sandbox Code Playgroud)

比如注册事件发生时调用的事件处理程序.

所有依赖于可用数据的代码都需要正确链接.

最简单的方法是转移代码 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    
  }
Run Code Online (Sandbox Code Playgroud)

  • @GünterZöchbauer 还有其他方法可以等待响应以打字稿形式到达吗? (2认同)