我是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"); }
以及使用它的组件并将其存储到阵列中的组件
....... 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[]'.)
解决方法
ngOnInit() { this.userService.getUser() .map((user: Array<any>) => { let result:Array<User> = []; if (user) { user.forEach((erg) => { result.push(new User(erg.nickname,erg.city )); }); } return result; // <<<=== missing return }) .subscribe(user => this.user = user); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。