parsing JSON into a Angular 2 object

前端 未结 1 755
青春惊慌失措
青春惊慌失措 2020-12-22 04:48

I am having the following issue.

I have a very large JSON string that has all the variables from the object.

object:

export class User {
             


        
相关标签:
1条回答
  • 2020-12-22 05:22

    In the world of Angular2, you should be using rxjs to achieve your requirement, as shown below

    Your component should subscribe to the service values as below

    this.userService.getUsers()
                  .filter(users =>{
                    for(let user of users) {
                        if(user.lastName == 'Vernon'){
                    this.users.push(user);
                   }}})
                  .subscribe(users => this.users = users,
                  error =>this.errorMessage =<any> error);
    

    Your service should raise http calls and return data as below

    import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import {User} from './user.model.ts';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/do';
    import 'rxjs/add/operator/filter';
    @Injectable()
    export class UserService {
        private _url = "src/data.json";
        constructor(private _http: Http) {
        }
        getUsers(): Observable<User[]> {
            return this._http.get(this._url)
                .map((response: Response) => <User[]>response.json())
    
                .do(data => console.log("User data" + JSON.stringify(data)))
                .catch(this.handleError);
        }
    
        private handleError(error: Response) {
                console.log(error);
                return Observable.throw(error.json().error || 'Internal Server error');
        }
    }
    

    Also, you should not use Class for holding your data model, instead use interface as shown in the demo below.

    LIVE DEMO

    0 讨论(0)
提交回复
热议问题