gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:57:29 73 4
gpt4 key购买 nike

promise 会返回一个值,但我似乎没有在订阅方法中正确分配值。

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() 向服务器发出请求时,需要花费很长的时间,直到响应到达并且可观察对象调用传递给 subscribe(... ) (res => this.companyCount = res.count).

构造函数、ngOnInitngAfterViewInit() 和许多其他内容的执行将在响应到达之前发生。

可以看到

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

就像注册一个在事件发生时被调用的事件处理程序。

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

最简单的方法是将代码移动到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 - 无法在 Angular 2 中使用 subscribe() 方法为变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39502775/

73 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com