2017-03-07 123 views
1

我遇到以下问题。将JSON解析为Angular 2对象

我有一个非常大的JSON字符串,它具有来自对象的所有变量。

对象:

export class User { 
    ssn:string; 
    userId:string; 
    firstName:string; 
    lastName:string; 
    middleName:string; 
    office:string; 
    role:string; 
    lockCode:string; 
    command:string; 
    street:string; 
    city:string; 
    position:string; 
    zip:string; 
    phone:string; 
    dsn:string; 
    fax:string; 
    email:string; 
    pwEffectiveDate:any; 
    pwVaildationDate:any; 
    fromDate:any; 
    toDate:any; 
    systemAccess:string; 
    dmType:string; 
    accessInfoEffectiveDate:any; 
    accessInfoEffectiveTo:any; 
    availableOffices: string[]; 
    availbleRole:string[]; 

} 

JSON:

@Injectable() 
export class SearchService { 

    getData() :any[] { return [ 
     {"snn": "26999935-7", "userId": "EVD404", "firstName": "Chaney", "lastName": "Vernon", "middleName": "X", "office": "ADURT", "role": "GC", "lockCode": "Q", "command": "5th Grp", "street": "953-1348 Faucibus Rd.", "city": "Bienne-lez-Happart", "position": "Developer", "zip": "76222", "phone": "233-969-1834", "dsn": "359-887-4719", "fax": "157-376-6377", "email": "[email protected]", "pwEffectiveDate": "13/03/17", "pwVaildationDate": "27/01/18", "fromDate": "10/11/17", "toDate": "21/12/17", "systemAccess": "GC", "dmType": "XJ", "accessInfoEffectiveDate": "26/12/2016", "accessInfoEffectiveTo": "06/06/2016", "availableOffices": "UUU", "availbleRole": "GC"}, 
     {"snn": "43250813-7", "userId": "NSB626", "firstName": "Addison", "lastName": "Vernon", "middleName": "X", "office": "AUTRO", "role": "GC", "lockCode": "O", "command": "11th ACR", "street": "Ap #904-5416 Semper, Road", "city": "s Herenelderen", "position": "Developer", "zip": "26457", "phone": "890-600-3144", "dsn": "679-122-1054", "fax": "913-500-7495", "email": "[email protected]", "pwEffectiveDate": "11/06/17", "pwVaildationDate": "01/03/17", "fromDate": "05/08/17", "toDate": "29/09/16", "systemAccess": "LIMIT", "dmType": "NB", "accessInfoEffectiveDate": "19/04/2017", "accessInfoEffectiveTo": "13/04/2016", "availableOffices": "LLL", "availbleRole": "USER"}, 

然后,我希望能够调用像下面的方法时,我通过我的服务到组件:

getUserByLastName(lastName):User[]{ 

     let temp: User[]=[]; 

     for(let d of this.data) { 
      if(d.lastName == lastName){ 
       temp.push(d); 
      } 
     } 

     return temp; 

    } 

我已尝试JSON.parse,但没有奏效。我尝试了其他一些东西,但没有一个似乎坚持。

--------------------------------- Update 1 ----------- -----------------

它引起了我的注意,我应该使用Observable。以下是我在试图实现这一点,但它是目前没有工作:

getUserBySSN():Observable<User[]> { 
     return this._http.get(this._url) 
      .map((response: Response) => 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'); 
    } 

我创建了一个JSON文件和设置可变url作为其路径。不过我正在给以下错误:

The type argument for type parameter 'T' cannot be inferred from the 
usage. Consider specifying the type arguments explicitly. Type 
argument candidate 'Response' is not a valid type argument because it 
is not a supertype of candidate 'Response'. Types of property 'type' 
are incompatible. Type 'string' is not assignable to type 'ResponseType' 

有人建议我用.map((response: Response) => <User[]> response.json())但我不会允许将其转换。

经过进一步的研究,我发现这是最好的方法,并试图让它起作用,所以稍后我可以使用它来对数据库进行实际的HTTP调用。

+0

你可以给使用JSON.parse的一个例子,它不工作? – snorkpete

+0

你为什么不在服务中使用Observable? – Aravind

+0

如何以及从哪里获取服务中的数据? – OmarIlias

回答

3

在Angular2的世界里,你应该用rxjs达到您的要求,如下图所示

你的组件应该订阅服务值如下

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); 

你的服务要提高http调用和返回数据如下

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'); 
    } 
} 

此外,你不应该使用类持有你的dat一个模型,而不是使用接口,如下面的演示所示。

LIVE DEMO

+0

请参阅更新一个。我们可以进入聊天室吗?非常感谢您的宝贵时间。 – Drew1208

+0

仍然没有意义,地图的结果仍然是一个Object类,如果你在模型用户中创建一个函数并在结果中调用它,它会抛出undefined –

+0

@TaDuyAnh你能发布一个抛出未定义的plunker吗?你看到过plunker演示吗? – Aravind