我是Angular(以及Javascript)的新手。我已經編寫了一個返回一組用戶的Angular服務。數據是從HTTP調用中獲取的,該調用以JSON格式返回數據。當記錄從HTTP調用返回的JSON數據時,我可以看到這個調用成功並返回了正確的數據。我有一個調用服務來獲取用戶的組件和一個顯示用戶的HTML頁面。我無法從服務中獲取數據到組件。我懷疑我錯誤地使用了Observable。也許我也錯誤地使用了訂閱。如果我在ngInit函數中註釋掉getUsers調用,並取消註釋getUsersMock調用,那麼一切正常,並且我看到數據顯示在HTML頁面的列表框中。我想將JSON數據轉換爲服務中的數組或用戶列表,而不是從服務返回JSON並讓組件將其轉換。從Angular服務獲取對象數組
數據來自HTTP調用返回讓用戶:
[
{
"firstName": "Jane",
"lastName": "Doe"
},
{
"firstName": "John",
"lastName": "Doe"
}
]
user.ts
export class User {
firstName: string;
lastName: string;
}
用戶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(): 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的值時,它報告未定義。
這是我的新的用戶,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();
}
}
...
!!!!!!!!!!最終工作解決方案!!!!!!!!!! 這是最終的工作溶液中的所有文件:
user.ts
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'));
}
}
user.component.ts
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();
}
}
你說得對。考慮添加工作示例。 – Sefa
您可以使用英雄教程中的工作示例。它工作得很好。 https://angular.io/resources/live-examples/toh-6/ts/plnkr.html – jmachnik
謝謝jmachnik。我用更多的信息更新了我的問題。我的代碼看起來是這樣做的原因是我最初實現它就像在英雄教程中所描述的,但是在組件中我的用戶[]變得'未定義',所以我去嘗試其他的東西。代碼現在看起來像英雄教程,但我仍然沒有定義。任何線索? –