数组 – 从Angular服务获取对象数组

前端之家收集整理的这篇文章主要介绍了数组 – 从Angular服务获取对象数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是Angular的新手(和Javascript一样).我写了一个Angular服务,它返回一个用户数组.从HTTP调用中检索数据,该调用以JSON格式返回数据.记录从HTTP调用返回的JSON数据时,我可以看到此调用成功并返回正确的数据.我有一个调用服务来获取用户的组件和一个显示用户的HTML页面.我无法将数据从服务获取到组件.我怀疑我正在使用Observable.也许我也正在使用订阅错误.如果我在ngInit函数中注释掉getUsers调用并取消注释getUsersMock调用,那么一切正常,我看到HTML页面中列表框中显示的数据.我想将JSON数据转换为服务中的数组或用户列表,而不是从服务返回JSON并让组件转换它.

从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的值时,它会报告undefined.

这是我修改过的user-service.ts

...
@Injectable
export class UserService {
    private USERS: User[] = [
        {
            firstName: 'Jane',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();
    }
}
看看你的代码
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已经返回一个observable,你不需要像在这里那样包装另一个Observable:

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再次构建您的服务.

原文链接:https://www.f2er.com/angularjs/143466.html

猜你在找的Angularjs相关文章