将JSON解析为Angular 2对象

将JSON解析为Angular 2对象,json,angular,Json,Angular,我有以下问题 我有一个非常大的JSON字符串,其中包含来自对象的所有变量 对象: export class User { ssn:string; userId:string; firstName:string; lastName:string; middleName:string; office:string; role:string; lockCode:string; command:string; street:

我有以下问题

我有一个非常大的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": "mauris.rhoncus@rhoncusDonec.com", "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": "Aenean@molestiesodales.com", "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,但没有成功。我尝试了一些其他的方法,但没有一种能坚持下去

---------------------------------更新1----------------------------

我已经注意到我应该使用一个可观察的。以下是我在尝试实现这一点时所做的,但它目前不起作用:

  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');
    } 
有人建议我使用
.map((response:response)=>response.json())
,但不允许我转换它


经过进一步研究,我发现这是最好的方法,我正在尝试让它发挥作用,以便稍后我可以使用它对数据库进行实际的HTTP调用

在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);
this.userService.getUsers()
.filter(用户=>{
for(让用户对用户){
如果(user.lastName=='Vernon'){
this.users.push(用户);
}}})
.subscribe(users=>this.users=users,

error=>this.errorMessage=

你能给出一个使用JSON.parse但它不起作用的例子吗?你为什么不在你的服务中使用Observable?你是如何从你的服务中获取数据的?从哪里获取数据?@omariias目前我在服务中有JSON
getData():any[]{return[JSON objects]
我想获取
getData
并在我的服务中初始化一个变量
private data=[]
所以我可以在我的服务方法中使用它。现在这些都只是模拟数据。@Drew1208您的意思是:当我将我的服务传递到组件中时,我希望能够调用下面这样的方法。现在,
这个。数据是在您的服务中还是在您的组件中?请查看更新一个。我们可以进入聊天室吗?非常感谢r您的时间。仍然没有意义,映射的结果仍然是一个对象类,如果您在model user中创建一个函数并在结果中调用它,它将抛出undefined@TaDuyAnh你能发布一个抛出未定义的plunker吗?你看到plunker演示了吗?
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);
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');
    }
}