我是角度2中的新角色,我花了很多時間來尋找解決方案,但是我沒有。我想從一個類的http調用存儲中轉換一個可觀察的元素。我想將角度2觀察值轉換爲類
我有以下幾點:
JSON文件
[{
"nickname": "magicMike",
"id": "123",
"name": "Michael",
"nachname": "Fischer",
"pictURL": "../images/mainPanel/Image_dummy.jpg",
"city": "Ulm"
}]
的用戶類文件:
export class User {
nickname: string;
id: string;
name: string;
nachname: string;
pictURL: string;
city: string;
constructor(
nickname: string,
id: string,
name: string,
nachname: string,
pictURL: string,
city: string
){
this.nickname = nickname;
this.id = id;
this.name = name;
this.nachname = nachname;
this.pictURL = pictURL;
this.city = city;
}
}
它讀取一個JSON文件服務
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { User } from './user'
@Injectable()
export class UserService {
user: Array<User>;
private useUrl = '/json/user.json';
constructor(private http: Http) {
}
getUser(): Observable<any> {
return this.http.get(this.useUrl)
.map(this.extractData)
.do(data => console.log("User from json: " + JSON.stringify(data)))
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response.json();
return body || {};
}
private handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || "500 internal server error");
}
而且組件其中採取oberservable並將其存儲到一個陣列
.......
export class AppComponent implements OnInit {
public user: User[];
ngOnInit() {
this.userService.getUser()
.map((user: Array<any>) => {
let result:Array<User> = [];
if (user) {
user.forEach((erg) => {
result.push(new User(erg.nickname, erg.id, erg.name, erg.nachname, erg.pictURL, erg.city));
});
}
})
.subscribe(user => this.user = user);
}
....
當我運行此我得到以下錯誤。
C:/Users/Lenovo/Documents/ui-challenger.one/src/app/app.component.ts (53,26): Type 'void' is not assignable to type 'User[]'.)
我希望在那裏的任何人都可以幫助我。我只是想分析JSON文件,到我可以讀這樣的「User.name」
非常感謝!這有幫助!還有一個問題。我想我現在可以使用例如{{user.name}}在模板上使用該用戶,但它不起作用。我很困惑!?對不起,我是打字稿的新手。 –
我想你只需要'{{user?.name}}'以避免錯誤,而'用戶'仍然是'空'(直到數據從服務器到達)。 –
再次感謝,如果我使用{{user?.name}},它是正確的:它工作:-)我驚訝,因爲我正在閱讀本地文件,我也想ngOnInit是在重新排序之前..... hmmm好的,謝謝你的快速幫助...... –