在Angular2中访问JSON

时间:2016-09-24 04:56:49

标签: json angular

我很难理解如何在Angular2中访问JSON对象的不同方面。特别是,我有一个我构建的Web API,它返回有关我服务器上硬盘驱动器详细信息的以下JSON对象:

enter image description here

图片是Chrome浏览器中使用httpService和Observable将其推送到控制台之后的屏幕截图,但了解如何获取特定信息却让我迷失了。

如果有人能指出我正确的方向,我们将不胜感激。

2 个答案:

答案 0 :(得分:3)

订阅http Observable后,您已经获得了实际对象。 假设您的http get请求如下所示:

this.httpService.get(this.apiUrl);

你可以使用rxjs Observables的强大功能,例如在这个对象上映射:

this.httpService.get(this.apiUrl) .map(res => res.json()) .map(body => body.Data) .map(data => data[0].AvailableSpace)

subscribing之后返回AvailableSpace

.subscribe(availablespace => console.log(availablespace);

注意访问这样的数组,这只是为了给你一个关于如何访问和操作observables中的对象的例子。

查看此网站,了解有关不同观察结果的更多信息 运算符,map以外的运算符。 https://www.learnrxjs.io/

答案 1 :(得分:1)

让我试试运气。希望它能帮助人们更好地理解。特别是,我将讨论如何在Angular 2中执行获取请求。在单独的获取发布请求中总是更好官方文档中提到的名为 service.ts 的文件。

我们将有三个文件,即 example.component.ts example.service.ts 和模型文件 examplemodel.ts

<强> example.component.ts

import {OnInit, Component} from "@angular/core";
import {ExampleService} from "./example.service"; // import service
import {ResponseFromGet, ErrorMessage} from "./examplemodel"; // import your model
@Component({
  providers: [ExampleService], // add your service here in order to use in component file
  templateUrl: './example.template.html'
})
export class ExampleComponent implements OnInit{
 //Specify Url for Get request
 Private _getRequestUrl = "http://entergetrequesturlhere";

// Make variable for stroing get method reponse which can be used in ur template file
 responseFromGetMethod: ResponseFromGet; // this can be ur model file which represnts ur JSON model

// For storing Error
  errorMessage: ErrorMessage;

//use Constructor to inject your service in component file
constructor(private _exampleService: ExampleService){}

// Since we implemented OnInit we need to override its method ngOnInit
// this method is called when page is loaded
  ngOnInit(): any{
    this.callGetMethod(this._getRequestUrl);
  }

// callGetMethod outside OnInit but inside class ExampleComponent
  callGetMethod(getUrl: string){
    this._exampleService.getMethodName(getUrl)
      .subscribe(
         responseFromGetMethod => {
           this.responseFromGetMethod = responseFromGetMethod; // Store response from getmethod in your local variable
         },
         error => this.errorMessage = <any>error // Store error message receiver from server
         );
  }
}

<强> example.service.ts

import {Http, Response} from "@angular/http";
import {Injectable} from "@angular/core";
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import {ResponseFromGet} from "./examplemodel";
@Injectable()
export class ExampleService{
   constructor(private _http: Http) { }

   // GET request To access data and specify observable type from model
  getMethodName(getUrl): Observable<ResponseFromGet>{
    return this._http.get(getUrl)
     .map(this.extractData) // to check for the status code
     .catch(this.handleError); // to check error
  }

  // Extracts from response
  private extractData(res: Response) {
     if (res.status < 200 || res.status >= 300) {
       throw new Error('Bad response status: ' + res.status);
     }
     let response = res.json();
     return response || {};
  }

  // To handle Error
  private handleError(error: Response) {
     console.error(error);
     return Observable.throw(error.json() || 'Server error');
  }
}

<强> examplemodel.ts

export interface ResponseFromGet{
  id: number;
  name: string;
}
export interface ErrorMessage{
  message: string;
}

最后是HTML文件 的 example.template.html

<div>
  <h2>{{responseFromGetMethod?.name}}</h2> // this will print the name from the json file
  <h3>{{errorMessage?.message}}</h3> // this will print the error if any
</div>

最后,这是我的 JSON 文件的模型

{
  "id": 789;
  "name": "Angular2";
}