[arrays] Getting an object array from an Angular service

I am new to Angular (and Javascript for that matter). I've written an Angular service which returns an array of users. The data is retrieved from an HTTP call which returns the data in JSON format. When logging the JSON data returned from the HTTP call, I can see that this call is successful and the correct data is returned. I have a component which calls the service to get the users and an HTML page which displays the users. I cannot get the data from the service to the component. I suspect I am using the Observable incorrectly. Maybe I'm using subscribe incorrectly as well. If I comment out the getUsers call in the ngInit function and uncomment the getUsersMock call, everything works fine and I see the data displayed in the listbox in the HTML page. I'd like to convert the JSON data to an array or list of Users in the service, rather then returning JSON from the service and having the component convert it.

Data returned from HTTP call to get users:

[
    {
        "firstName": "Jane",
        "lastName": "Doe"
    },
    {
        "firstName": "John",
        "lastName": "Doe"
    }
]

user.ts

export class User {
    firstName: string;
    lastName: string;
}

user-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>
...

!!! UPDATE !!!

I had been reading the "heroes" tutorial, but wasn't working for me so I went off and tried other things. I've re-implemented my code the way the heroes tutorial describes. However, when I log the value of this.users, it reports undefined.

Here is my revised user-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(): Promise<User[]> {
        return this.http.get('http://users.org')
            .toPromise()
            .then(response => response.json().data as User[])
            .catch(this.handleError);
    }
...

Here is my revised 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();
    }
}
...

!!!!!!!!!! FINAL WORKING SOLUTION !!!!!!!!!! This is all the files for the final working solution:

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

This question is related to arrays json angular rxjs angular2-http

The answer is


Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.


Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to rxjs

Angular - "has no exported member 'Observable'" What is pipe() function in Angular How to convert Observable<any> to array[] TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable What is the difference between Subject and BehaviorSubject? Best way to import Observable from rxjs take(1) vs first() Observable Finally on Subscribe Getting an object array from an Angular service BehaviorSubject vs Observable?

Examples related to angular2-http

Difference between HttpModule and HttpClientModule How to correctly set Http Request Header in Angular 2 Getting an object array from an Angular service File Upload In Angular? Angular: Cannot find a differ supporting object '[object Object]' Angular2: How to load data before rendering the component? Angular - POST uploaded file