2016-12-17 26 views
1

我有一個AngularJS 2應用程序,我想運行一個http調用並在啓動和結束時設置一些變量。問題是我需要在不同地點爲同一個電話進行此操作。在多個位置的http調用開始和結束處設置變量

constructor(
    private http: Http 
) {} 

fetch() { 
    return this.http 
    .get('assets/data/events.json') 
    .map(response => response.json()); 
} 

load() { 
    let isLoading = true; // set variable at start 
    return this.fetch() // call fetch() 
    .finally(() => isLoading = false); // set variable at end 
} 

reload() { 
    let isReloading = true; // set variable at start 
    return this.load() // call load() 
    .finally(() => isReloading = false); // set variable at end 
} 

this.reload(); // start call 

當我調用的重載()函數load()和重載(的)的開始和結束變量必須在同一時間對同一HTTP調用來設置。我怎樣才能做到這一點?

回答

0

我解決這樣說:

constructor(
    private http: Http 
) {} 

fetch() { 
    return this.http 
    .get('assets/data/events.json') 
    .map(response => response.json()); 
} 

load() { 
    let share = this 
    .fetch() 
    .share(); 
    let isLoading = true; // set variable at start 
    share 
    .finally(() => isLoading = false) // set variable at end 
    .subscribe(); 
    return share; 
} 

reload() { 
    let isReloading = true; // set variable at start 
    return this.load() // call load() 
    .finally(() => isReloading = false) // set variable at end 
    .subscribe(); 
} 

this.reload(); // start call 
1

試試這個。

isLoading: Boolean = false; 
    isReloading: Boolean = false; 
    constructor(private http:Http) { 
    } 
    fetch() { 
     return this.http 
     .get('assets/data/events.json') 
     .map(response => response.json()); 
    }  
    load() { 
    this.isLoading = true; // set variable at start 
    this.fetch() // call fetch() 
    .finally(() => this.isLoading = false); // set variable at end 
    }  
    reload() { 
     this.isReloading = true; // set variable at start 
     this.load() // call load() 
    .finally(() => this.isReloading = false); // set variable at end 
    } 
    this.reload(); 
+0

這是行不通的。我會用我找到的解決方案發布答案​​。 –

相關問題