2

I am newbie to Angular2 and Typescript. I am learning nowadays. I try to get data from a REST service then I want to make a list and insert this data which comes from the service. So my API link is http://jsonplaceholder.typicode.com/users/1

here is my HttpTestService.ts code;

import {Component} from '@angular/core';
import {Http} from '@angular/http';
import {Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import 'rxjs/add/operator/map';

@Injectable()
export class HTTPTestService{
  constructor(private _http:Http){}
    getUser(){
      return this._http.get("http://jsonplaceholder.typicode.com/users/1")
      .map(res=>res.json());
    };
}}

Here is my HttpTestComponent.ts;

import { Component } from '@angular/core';
import {HTTPTestService} from './http-test.service';
import { User } from './user';

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Post Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Get Data(w Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>
  `,
  providers:[HTTPTestService]
})

export class HTTPTestComponent{
  getData:string;
  getPromiseData:string;
  postData:string;


  constructor(private _httpService:HTTPTestService){}

  onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(        
      data =>this.getData = JSON.stringify(data),
      error=>alert(error),
      ()=>console.log('Finished Get')      
    );         
  }}

And here is my User.ts

 export class User{
  constructor(public id: number,public name:string) { }
 }

How do I fill my User class and then how do I add a generic list to my User class.

Best regards

4
  • Do you want to create a new object with id and name only or use whole structure received from server? Commented Nov 16, 2017 at 11:44
  • server send many paramaters but i just only fill id and name to my structure. is it possible or i should write all parameter which server send ? Commented Nov 16, 2017 at 11:52
  • No, you don't have to, and tell me more about generic list in User class, what do you mean by this? Commented Nov 16, 2017 at 11:56
  • like csharp; var myUserlist = new List<User>(); myUserList.add(new User{id = 1,name = "aaa"}) this new User fill from by rest Commented Nov 16, 2017 at 11:56

1 Answer 1

3

As far as I understand your question, just create a new Object of User type and pass desired data, in your case it is id and name.

private userList: Array<User> = new Array<User>();

onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(        
      data => this.parseUser(data),
      error=>alert(error),
      ()=>console.log('Finished Get')      
    );         
  }

parseUser(data) {
   let user = new User(data.id, data.name);
   this.userList.push(user);
}

To create list of users just make an array of User like that private Users: Array<User> = new Array<User>(); remember to import User.

EDIT. For test purpose change this

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Post Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Get Data(w Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>

    <div *ngFor="let user of userList">
       <p>Id: {{user.id}}</p>
       <p>Name: {{user.name}}>/p>
       <br />
    </div>
  `,
  providers:[HTTPTestService]
})

When response come angular will print data :)

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

11 Comments

data => parseUser(data), should be data => this.parseUser(data) ?
thanks for your answer but when turn list it comes nothing; console.log('Start List') for (var v in this.userList) { console.log("My First Element: "+ this.userList[v].id); } console.log('End List') userList.Length = 0. I think it didnt parse or it didnt push correctly. Because i get data before parsing. where am i wrong ?
That's strange, maybe you have a typo, check you console for errors and I would like suggest you to use for .. of .. loop for example it would be for(let user of this.userList) { console.log("user id: " + user.id) }
Userlist.length = 0; so it didnt write anything ? are you sure that this parse method working fine ? Because you dont use any Json.parse etc ?
Referring to your service getUser(){ return this._http.get("http://jsonplaceholder.typicode.com/users/1") .map(res=>res.json()); }; is parsing it to JSON :). remember that evaluating callback for subscribe is asynchronous so check the place where you are calling this or show me the code :).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.