我正在学习Angular 2,我需要将我的服务结果分配给组件构造函数中的数据变量。 如何在构造函数中使用订阅数据并将此值分配给我的公共数据数组?
public data: Array<any> =[];
public constructor(private _languageService: LanguageService){
this._languageService.getLanguages()
.subscribe(languages => {this.languages =languages;}
,error => this.errorMessage = <any>error)
this.length = this.data.length;
//How i can set this.data = this.languages
//if this.languages is empty outside the subscribe?
}
如果有人能向我解释如何将服务返回的数据分配给变量,我真的很感激。
答案 0 :(得分:2)
我们必须在.subscribe()
public data: Array<any> =[];
public constructor(private _languageService: LanguageService){
this._languageService
.getLanguages()
.subscribe(languages => {
this.languages =languages;
[].push.apply(this.data, languages);
},error => this.errorMessage = <any>error)
...
}
构造[].push.apply(target, source)
会将所有即将到来的值推送到现有数组引用
EXTEND
我们可以通过 observable 源加载数据,然后在可用时使用。我们在模板中使用*ngIf
<div>
<some-component
*ngIf="myData"
[bindSource]="myData"
...
></some-component>
</div>
在组件中我们可以订阅获取该数据:
public myData: any[] =[];
public constructor(private _languageService: LanguageService){
this._languageService
.getLanguages()
.subscribe(languages => {
this.myData = languages;
});
}