访问Angular2对象?

问题描述:

我想保存并访问Angular2对象,但我得到的值未定义。我得到一个对象,但不能访问,如数组。我怎么能做到阵列?访问Angular2对象?

Node.js的api.js

api.get('/getData', function(req, res){ 
    res.send({name:'test'}) 
}); 

的DataService PassProfileDataService.ts

import {Component, Injectable} from '@angular/core' 
import { Http} from "@angular/http"; 


@Injectable() 
export class PassProfileDataService { 

constructor(private http: Http) {} 

getItems(){ 
    return this.http.get('/api/getData').map((res:any) => res); 
} 
} 

组件消耗的服务

import {Component, Input, OnInit} from '@angular/core'; 
import {PassProfileDataService} from '../common/PassProfileDataService'; 


@Component({ 
styleUrls:['/assets/css/bootstrap.css', '/assets/css/profile.css'], 
    selector: "profile", 
    templateUrl: `client/components/profile/profile.component.html` 

}) 

export class ProfileComponent implements OnInit { 

items:any; 

constructor(private _sharedService: PassProfileDataService){} 

ngOnInit(){ 
    this.items = this._sharedService.getItems(); 
    console.log(this.items + ' test'); 
} 

}

视图组件profile.component.html

<div *ngFor="let i of items"> 
{{i.name}} 
</div> 

我得到以下异常:

core.umd.js:3462 EXCEPTION:无法找到一个不同的支持对象“ [对象]类型的[对象对象]。 NgFor仅支持与阵列等Iterables绑定。

TypeScript允许您在定义函数时使用箭头符号访问外部函数作用域,方法是将参数括在括号中。

要保存数据的价值简单地使用:

this.items.subscribe((value) => this.data = value); 

并保存数据,然后尽快到达输出,你可以使用:

this.items.subscribe((value) => { 
    this.data = value; 
    console.log(this.data); 
}); 

this.items.subscribe(...)是异步这意味着它现在不会运行该代码。 this.items是一个Observable,简而言之,当最终发生某些事情时,可以通知您并在事件发生时“观察”事件或一系列事件。在这种情况下,它看起来很像对getUserWishList()的响应承诺。我写了很多看起来就像这样的代码。

如果一切按计划进行,最终观察到的订阅将会触发,并且this.data将等于value,但我可以保证当您尝试打印出来时不会在下一行发生。

this.items.subscribe(value => console.log(value));的作品,因为当事件最终发生火灾,你有价值,并可以打印它。

this.items.subscribe(value => this.data = value);也有效。最终。它不会像你期望的那样快。

你可以修改代码一点是既:

this.items.subscribe(value => { 
    this.data = value; 
    console.log(this.data); 
}); 

你会在控制台中看到的价值,如果有的话,势必this.data也应该反映在视图中的数据。这可能有点棘手,但如果您在视图中绑定data.name,如果this.data在Observable回来之前没有任何东西,则会出现错误。

+0

我正在以下错误客户端/组件/配置文件/ profile.component.ts(27,6):错误TS2322:类型“任何[]”是不能分配给输入“可观察”。 [1] client/components/profile/profile.component.ts(27,6):错误TS2322:类型'any []'不可分配给类型'Observable '。 [1]类型'any []'中缺少属性'_isScalar'。另外我怎样才能访问名称属性? – Tony

+0

@Tony,这是一个更复杂的打字问题,可能值得一个新的问题。你必须展示更多的代码才能看到getUserWishList实际返回的是什么(Observable,但是泛型是什么?即Observable >)以及真正的值是什么。 –

+0

@Tony,你的'console.log'图片在你的问题中看起来像'value'只是一个对象而不是数组。由此我认为价值是一个“任何”,“this.data”不应该是任何形式的可观察的,this.data应该只是一个“任何”。或者更好的是,一个正确定义的界面。 –

这是因为框架的异步行为。代码不会等待您的服务返回。它继续下一个陈述,在那个时间点,“数据”是未定义的。改变你的代码如下:

this.items.subscribe(value => this.data = value); 
console.log(this.data); 

到:

this.items.subscribe(value => { 
this.data = value; 
console.log(this.data); 
}); 

你看到区别?我将console.log移至success服务区块。这是使代码以同步方式运行的一种快速方法。当你需要的时候,还有其他的方法可以在你的代码中引入同步行为,例如Observable.forkJoin。希望你明白了。