我是Angular的新手(也是Java语言)。我已经编写了一个Angular服务,该服务返回一个用户数组。从HTTP调用检索数据,该HTTP调用以JSON格式返回数据。记录从HTTP调用返回的JSON数据时,可以看到此调用成功,并且返回了正确的数据。我有一个调用服务以获取用户的组件和一个显示用户的HTML页面。我无法从服务到组件获取数据。我怀疑我使用的Observable错误。也许我也使用了错误的订阅。如果我注释掉ngInit函数中的getUsers调用并取消注释getUsersMock调用,则一切正常,并且我看到HTML页面列表框中显示的数据。一世’
从HTTP调用返回的数据以获取用户:
[ { "firstName": "Jane", "lastName": "Doe" }, { "firstName": "John", "lastName": "Doe" } ]
用户名
export class User { firstName: string; lastName: string; }
用户服务
... @Injectable export class UserService { private USERS: User[] = [ { firstName: 'Jane', lastName: 'Doe' }, { firstName: 'John', lastName: 'Doe' } ]; constructor (private http: Http) {} getUsersMock(): User[] { return this.USERS; } getUsers(): Observable<User[]> { return Observable.create(observer => { this.http.get('http://users.org').map(response => response.json(); }) } ...
user.component.ts
... export class UserComponent implements OnInit { users: User[] = {}; constructor(private userService: UserService) {} ngOnInit(): void { this.getUsers(); //this.getUsersMock(); } getUsers(): void { var userObservable = this.userService.getUsers(); this.userObservable.subscribe(users => { this.users = users }); } getUsersMock(): void { this.users = this.userService.getUsersMock(); } } ...
user.component.html
... <select disabled="disabled" name="Users" size="20"> <option *ngFor="let user of users"> {{user.firstName}}, {{user.lastName}} </option> </select> ...
!!! 更新!!!
我一直在阅读“英雄”教程,但没有为我工作,因此我尝试了其他事情。我已经按照英雄教程描述的方式重新实现了我的代码。但是,当我记录this.users的值时,它报告未定义。
这是我修改后的user-service.ts
... @Injectable export class UserService { private USERS: User[] = [ { firstName: 'Jane', lastName: 'Doe' }, { firstName: 'John', lastName: 'Doe' } ]; constructor (private http: Http) {} getUsersMock(): User[] { return this.USERS; } getUsers(): Promise<User[]> { return this.http.get('http://users.org') .toPromise() .then(response => response.json().data as User[]) .catch(this.handleError); } ...
这是我修改后的user.component.ts
... export class UserComponent implements OnInit { users: User[] = {}; constructor(private userService: UserService) {} ngOnInit(): void { this.getUsers(); //this.getUsersMock(); } getUsers(): void { this.userService.getUsers() .then(users => this.users = users); console.log('this.users=' + this.users); // logs undefined } getUsersMock(): void { this.users = this.userService.getUsersMock(); } } ...
!!!!!!!!!! 最终的解决方案!!!!!!!!!! 这是最终工作解决方案的所有文件:
export class User { public firstName: string; }
user.service.ts
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { User } from './user'; @Injectable() export class UserService { // Returns this JSON data: // [{"firstName":"Jane"},{"firstName":"John"}] private URL = 'http://users.org'; constructor (private http: Http) {} getUsers(): Observable<User[]> { return this.http.get(this.URL) .map((response:Response) => response.json()) .catch((error:any) => Observable.throw(error.json().error || 'Server error')); } }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './user'; import { UserService } from './user.service'; @Component({ moduleId: module.id, selector: 'users-list', template: ` <select size="5"> <option *ngFor="let user of users">{{user.firstName}}</option> </select> ` }) export class UserComponent implements OnInit{ users: User[]; title = 'List Users'; constructor(private userService: UserService) {} getUsers(): void { this.userService.getUsers() .subscribe( users => { this.users = users; console.log('this.users=' + this.users); console.log('this.users.length=' + this.users.length); console.log('this.users[0].firstName=' + this.users[0].firstName); }, //Bind to view err => { // Log errors if any console.log(err); }) } ngOnInit(): void { this.getUsers(); } }
看一下你的代码:
getUsers(): Observable<User[]> { return Observable.create(observer => { this.http.get('http://users.org').map(response => response.json(); }) }
和来自https://angular.io/docs/ts/latest/tutorial/toh- pt6.html的代码 (顺便说一句,非常好的教程,您应该检查一下)
getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise() .then(response => response.json().data as Hero[]) .catch(this.handleError); }
Angular2内部的HttpService已经返回了一个可观察的对象,所以不需要像在这里那样包装另一个可观察的对象:
return Observable.create(observer => { this.http.get('http://users.org').map(response => response.json()
尝试按照我提供的链接中的指南进行操作。仔细学习后,您应该会很好。
- -编辑 - -
首先,在哪里记录this.users变量?JavaScript无法正常工作。您的变量是未定义的,这很好,因为代码执行顺序!
尝试这样做:
getUsers(): void { this.userService.getUsers() .then(users => { this.users = users console.log('this.users=' + this.users); }); }
查看console.log(…)在哪里!
尝试从toPromise()辞职,这似乎只是针对没有RxJs背景的ppl。
捕获另一个链接:https : //scotch.io/tutorials/angular-2-http-requests-with- observables使用RxJs observables再次构建您的服务。