Angular 2 Typescript将json解析为object

时间:2017-11-16 11:41:28

标签: angular typescript

我是Angular2和Typescript的新手。我现在正在学习。我尝试从REST服务获取数据然后我想创建一个列表并插入来自该服务的数据。 所以我的API链接是http://jsonplaceholder.typicode.com/users/1

这是我的HttpTestService.ts代码;

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

这是我的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')      
    );         
  }}

这是我的User.ts

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

如何填写我的User课程,然后如何在我的User课程中添加通用列表。

祝你好运

1 个答案:

答案 0 :(得分:3)

据我了解您的问题,只需创建一个新的Object User类型并传递所需的数据,在您的情况下为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);
}

要创建用户列表,只需创建一个User数组 private Users: Array<User> = new Array<User>();请记得导入User

EDIT。 出于测试目的,请更改此

@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]
})

当响应到来时angular将打印数据:)