Angular - 从json占位符获取标题列表

时间:2017-07-05 17:28:13

标签: javascript json angular

我用Angular版本4创建了一个简单的服务,我返回一个带有几个标题的数组:

以下是代码:

//post.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class PopstService {

  constructor() {}

  showPosts() {
    return ['title1', 'title2', 'title3'];
  }

}

我没有在服务页面中对其进行硬编码,而是希望从某些json数据中添加标题。

这是网址:

https://jsonplaceholder.typicode.com/posts

数据如下所示:

0   
userId  1
id  1
title   "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
body    "quia et suscipit\nsuscip… rem eveniet architecto"
1   
userId  1
id  2
title   "qui est esse"
body    "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"

如何修改此服务以从在线json而不是我当前的硬编码标题中返回标题?

1 个答案:

答案 0 :(得分:1)

步骤1.创建服务

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/operator/map';
import  'rxjs/add/operator/do';
import  'rxjs/add/operator/catch';

@Injectable()
export class ProductService{
  private _productUrl = 'api url';
  constructor (private _http:Http){}

  getProductsHttp():Observable<any> {
      return this._http.get(this._productUrl)
          .map((response: Response) => <any> response.json())
          .do(data => console.log('All: ' +  JSON.stringify(data)))
          .catch(this.handleError);
  }

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

步骤2更改下面的组件

constructor(private _producrService:ProductService)  {

  }
  ngOnInit() {
      //this.products=this._producrService.getProducts();
      this._producrService.getProductsHttp()
              .subscribe(products => this.products = products,
                         error => this.errorMessage = <any>error);

  }