gpt4 book ai didi

angular - 我想将 angular2 observable 转换为一个类

转载 作者:太空狗 更新时间:2023-10-29 17:20:51 28 4
gpt4 key购买 nike

我是 angular2 的新手,我花了很多时间来寻找解决方案,但我没有。我想从一个类中的 http 调用存储转换一个 oberservable。

我有以下内容:

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”的属性

最佳答案

 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 ));
});
}
return result; // <<<=== missing return
})
.subscribe(user => this.user = user);
}

关于angular - 我想将 angular2 observable 转换为一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42190002/

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