json - 我如何处理 Angular 2 中的 JSON 数据?

标签 json wordpress http service angular

大家好,我是 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() 发出一个请求,获取数据并将其存储在某处,以便其他方法可以使用该数据并执行它们的特定操作。

谢谢

最佳答案

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

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

关于json - 我如何处理 Angular 2 中的 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35618192/

相关文章:

php - 编辑我的帐户导航菜单编辑地址链接

css - 如何将横幅广告移到 960 像素宽度之外

jquery - 如何使用 jquery 从没有任何 id 或类的 div 中删除 anchor 标记?

api - 如何在客户端 javascript 中使用 Grafana Http API

http - 我可以每天更改一个网站图标吗

java - 在不使用 @JsonTypeInfo 的情况下使用 Jackson 反序列化为多态集合

json - 将 JSON 文件从 URL 导入 R

json - package.json 中带有 sed 的 Bump 版本

json - 使用RJSONIO::fromJSON()简化POSIX节点

multithreading - 如何在http中使用多个进程