我想保存並訪問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綁定。
我正在以下錯誤客戶端/組件/配置文件/ profile.component.ts(27,6):錯誤TS2322:類型「任何[]」是不能分配給輸入「可觀察」。 [1] client/components/profile/profile.component.ts(27,6):錯誤TS2322:類型'any []'不可分配給類型'Observable '。 [1]類型'any []'中缺少屬性'_isScalar'。另外我怎樣才能訪問名稱屬性? –
Tony
@Tony,這是一個更復雜的打字問題,可能值得一個新的問題。你必須展示更多的代碼才能看到getUserWishList實際返回的是什麼(Observable,但是泛型是什麼?即Observable >)以及真正的值是什麼。 –
@Tony,你的'console.log'圖片在你的問題中看起來像'value'只是一個對象而不是數組。由此我認爲價值是一個「任何」,「this.data」不應該是任何形式的可觀察的,this.data應該只是一個「任何」。或者更好的是,一個正確定義的界面。 –