2017-03-09 86 views
0

我有一個api調用類別,一切正常。現在,如果我需要另一個頁面中的類別,則需要再次撥打電話,而我需要將其存儲在本地。 我只是遵循了我在angular1中練習的方法,但是它的投擲錯誤。評論線是我的試驗。避免重複API調用angular2

private categories: any; 
    constructor(private http: Http) { } 

    getCategories(): Promise<any> { 
    // if(!this.categories){ 
    return this.http.get(environment.API_ENDPOINT + 'categories') 
     .toPromise() 
     .then(this.extractData) 
     .catch(this.handleError); 
    // }else{ 
    // console.log("call blocked"); 
    // return Promise.resolve(this.categories); 
    // } 

    } 


    private extractData(res: Response) { 
    let body = res.json(); 
    // this.categories = body || []; 
    return body; 
    //return this.categories; 
    } 

    private handleError(error: any): Promise<any> { 

    return Promise.reject(JSON.parse(error.message || error._body || error)); 
    } 

如何存儲API接收到的數據,所以我撥打服務,它將檢查以前的數據,如果沒有可用的,它將從服務器上獲取數據。

在此先感謝。

與觀察到的嘗試的

import { Injectable } from '@angular/core'; 

import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/observable/of'; //updating import library, which threw error 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/share'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/publishReplay' 
import {Cities} from '../interface/cities'; 
import { environment } from '../../environments/environment'; 
@Injectable() 
export class CityService { 
    private endPoint = environment.API_URL+'cities'; 
    private data:any; 
    constructor(
    private http: Http) { } 

    getAll(): Observable<Cities[]> { 
    if(this.data){ 
     return Observable.of(this.data); // 
     } 
    return this.http.get(this.endPoint) 
        .map(this.extractData) 
        .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
    let body = res.json(); 
    this.data = body || body.data || { }; 
    return this.data; 
    } 
    private handleError (error: Response | any) { 
    // In a real world app, we might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 

} 

鬥爭後,我只發現這是一個有效的解決方案給我2天發佈計數

import { Injectable } from '@angular/core'; 

import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/observable/of'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/share'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/publishReplay' 
import {Cities} from '../interface/cities'; 
import { environment } from '../../environments/environment'; 
@Injectable() 
export class CityService { 
    private endPoint = environment.API_URL+'cities'; 
    private data:any; 
    constructor(
    private http: Http) { } 

    getAll(): Observable<Cities[]> { 
    return this.http.get(this.endPoint) 
        .map(this.extractData) 
        .publishReplay(1) // does not stop duplicate calls 
        .refCount() // does not stop duplicate calls 
        .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
    let body = res.json(); 
    this.data = body || body.data || { }; 
    return this.data; 
    } 
    private handleError (error: Response | any) { 
    // In a real world app, we might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 

} 
+3

http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-結果的角2-http-network-call-in/36291681#36291681 –

+0

@GünterZöchbauer你可以看看我的更新,並告訴我錯在哪裏 –

+0

import'rxjs/add/observable/of' ;是錯誤的。我複製粘貼從堆棧溢出錯過添加的答案。不知道是否在以前的版本沒有添加 –

回答

1

Atlast嘗試和。

雖然我張貼着城市的一個問題,這與類別

import { Injectable } from '@angular/core'; 

import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/observable/of'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/share'; 
import 'rxjs/add/operator/map'; 
import { Cities } from '../interface/cities'; 
import { environment } from '../../environments/environment'; 
import { LocalStorageService } from 'angular-2-local-storage'; 
@Injectable() 
export class CityService { 
    private endPoint = environment.API_URL + 'cities'; 
    private data: any; 
    constructor(
    private http: Http, 
    private localStorageService: LocalStorageService) { } 

    getAll(): Observable<Cities[]> { 
    if (this.localStorageService.get('cities')) { 
     return Observable.of(this.localStorageService.get('cities')); 
    } else { 
     return this.http.get(this.endPoint) 
     .map(this.extractData) 
     .do((data) => this.localStorageService.set("cities", data)) 
     .catch(this.handleError); 
    } 
    } 
    private extractData(res: Response) { 
    let body = res.json(); 
    this.data = body || body.data || {}; 

    //this.localStorage.setItems$.subscribe("cities", "Hello world"); 
    return this.data; 
    } 
    private handleError(error: Response | any) { 
    // In a real world app, we might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 

}