【问题标题】:How do i handle JSON Data in Angular 2?如何在 Angular 2 中处理 JSON 数据?
【发布时间】:2016-02-25 04:13:56
【问题描述】:

您好,我是 Angular 的新手,我一直在努力学习 Angular 2,所以要温柔:)。 我一直在尝试使用 WP API 插件将 WordPress 用作我的数据 API。并且到目前为止能够从 WordPress 获取帖子。下面是我的数据服务代码。

import {Injectable} from "angular2/core";
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import {PostInterface} from './data.interface';
import {Headers} from "angular2/http";
import {RequestOptions} from "angular2/http";



@Injectable()
export class DataService{
    private _dataURL : string = 'http://localhost/wordpress/?rest_route=/wp/v2/posts';
    posts : PostInterface [];
    post : PostInterface;
    errorMessage : string;

    constructor(private http:Http){}

    getPosts():Observable<any[]>{
        //return this.http.get(this._dataURL).map((res:Response) => res.json());
        return this.http.get(this._dataURL)
            .map(res=>res.json())
            //.do(data => console.log(data)) // eyeball results in the console
            .catch(this.handleError);
    }

    //todo fix search

    getPost(filterid:number):Observable<any[]>{
         //filterid is the id of a specific post
        this._dataURL = this._dataURL + '/' + filterid;
        return this.http.get(this._dataURL)
            .map(res => res.json())
            .catch(this.handleError);
    }




    private handleError (error: Response) {

        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }

}

在代码中,我使用getPosts() 方法获取所有帖子数据,但我也有一个getPost() 方法来获取特定帖子。 我想知道是否可以使用getPosts() 获取的JSON 数据并在getPost() 方法中再次使用它。目前getPost() 所做的是再次调用http.get 我不想一次又一次地发出http.get 请求。

我希望getPosts() 发出一个请求,获取数据并存储在某处,以便其他方法可以使用数据并进行特定操作。

谢谢

【问题讨论】:

  • 如果你想将数据存储在某个地方,那么就存储它。那有什么问题。您可以使用变量将所有帖子保存为数组或地图,然后您可以从那里使用它。您还可以使用 localstorage 来缓存数据,这样您就不必在每次需要数据时都请求它。

标签: json wordpress http service angular


【解决方案1】:

是的,您可以首先获取所有数据并保存到一个变量中,或者您订阅数据的另一种方法是执行for loop 并与您的filterId 匹配,其中过程匹配将数据存储到数组中并根据您的操作实现需要。这是假设您的数据是数组形式的示例..

import {Injectable} from "angular2/core";
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import {PostInterface} from './data.interface';
import {Headers} from "angular2/http";
import {RequestOptions} from "angular2/http";

@Injectable()
export class DataService{
    private _dataURL : string = 'http://localhost/wordpress/?rest_route=/wp/v2/posts';
    posts : PostInterface [];
    post : PostInterface;
    errorMessage : string;

    constructor(private http:Http){}

    getPosts():Observable<any[]>{
        //return this.http.get(this._dataURL).map((res:Response) => res.json());
        return this.http.get(this._dataURL)
            .map(res=>{
              if(res.json()){
                return res.json()
              }
            });
            //.do(data => console.log(data)) // eyeball results in the console
            .catch(this.handleError);
    }


    // Method in any file where you want to subscribe your data and wanna fetch specific post //

    singlePost: Array<any>= [];

    methodName(filterid:number){

        service.getPosts()
         .subscribe(res=>{
            console.log(res)   // Here you data whihc is coming from .map i.e getPosts methods using Http

            for(let i=0; i< res.length ; i++){       // I am asuming your data is in array from so performing length functionality
                if(filterid == res[i].filterid){
                    this.singlePost = res[i];
                    break;
                }
            }

            console.log(this.singlePost)        // This will return your single Specific POst without using `Http` again and again
         })
    }

【讨论】:

  • 谢谢 Pardeep.. 我是新手,所以请耐心等待。在我的代码中, .getPosts() 方法在应用程序启动时获取所有数据,我的问题是我可以使用 .getPosts() 获取的数据并在 getPost() 方法中使用它,这样我就不必请求数据一次又一次地使用已经获取的数据??
  • @abizit 是的,在我的回答中,methodName 命名方法对你也有同样的作用。从.getPosts 发送的数据在方法名称methodName 中订阅,这样您就不需要一次又一次地使用http
【解决方案2】:

当收到getPosts 结果时,您可以尝试使用do 运算符将数据保存到您的服务中:

@Injectable()
export class DataService{
  private _dataURL : string = 'http://localhost/wordpress/?rest_route=/wp/v2/posts';
  posts : PostInterface [];
  post : PostInterface;
  errorMessage : string;

  constructor(private http:Http){}

  getPosts():Observable<any[]>{
    //return this.http.get(this._dataURL).map((res:Response) => res.json());
    return this.http.get(this._dataURL)
        .map(res=>res.json())
        .do(data => this.posts = data) // <--------
        .catch(this.handleError);
  }

  findPostById(id) {
    if (this.posts != null) {
      return this.posts.find(((element, index, array) {
        return (element.id = id);
      });
    } else {
      return null;
    }
  }

  getPost(filterid:number):Observable<any[]>{
    var post = findPostById(filterid);
    if (post != null) { // <--------
      return post;
    } else {
      this._dataURL = this._dataURL + '/' + filterid;
      return this.http.get(this._dataURL)
          .map(res => res.json())
          .catch(this.handleError);
    }
  }

请根据您的需要随意调整此代码。

【讨论】:

  • 谢谢蒂埃里,我想知道如果我想在 init 上加载所有数据并将其保存为全局数据,我该如何处理,以便我可以使用该数据本身按 id 过滤而不是制作一个不同的 http.get 请求。我希望它的工作方式是我只需要加载一次 API JSON,因为它包含我需要的所有数据。
  • 不客气!您可以将getPosts 方法的内容移动到服务的构造函数中,并更新此方法以返回this.posts。如果在bootstrap函数级别定义了服务的提供者,则在应用程序启动时执行服务的构造函数
  • 感谢您的快速回复.. 所以我也应该在引导程序本身上加载 DataService 对吗??
  • 是的,类似bootstap(AppComponent, [ DataService ]);。否则,它的实例化将链接到您定义它的组件实例化(providers 属性)。
猜你喜欢
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 2023-02-07
  • 2018-10-01
  • 1970-01-01
相关资源
最近更新 更多