1

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 {
    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"},

Then I want to be able to call methods like below when I pass my service into the component:

getUserByLastName(lastName):User[]{

        let temp: User[]=[];

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

        return temp;

    }

I have tried to JSON.parse but that did not work. I tried a few other things but none seem to stick.

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

It has been brought to my attention that I should be using an Observable. Here is what I have in trying to implement that but it is currently not working:

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

I created a json file and set the variable url as its path. However I am getting to following error:

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'

It was suggested I use .map((response: Response) => <User[]> response.json()) but I was not allow to convert it.

After further research I found this is the the best approach and am trying to get it to function so later on I can use it to do actual HTTP calls against the DB.

13
  • can you give an example of using JSON.parse and it not working? Commented Mar 7, 2017 at 18:40
  • why are you not using Observables in your service? Commented Mar 7, 2017 at 18:45
  • how and where are you getting the data from your service? Commented Mar 7, 2017 at 18:46
  • @OmarIlias currently I have the JSON in the service getData() :any[] { return [ JSON objects] I want to take getData and initialize a variable in my service private data = []; so I can use it in my service methods. This is all just Mock data right now. Commented Mar 7, 2017 at 19:12
  • @Drew1208 you're saying: Then I want to be able to call methods like below when I pass my service into the component. Now, this.data is it in your service or in your component? Commented Mar 7, 2017 at 19:15

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Please see update one. Can we go into the chat room? Thank you very much for your time.
Still not make sense, the result of the map is still an Object class, if you create a function in model user and call it in the result, it will throw undefined
@TaDuyAnh can you post a plunker that throws undefined? did you see the plunker demo?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.