2017-05-11 72 views
0

在我的代碼之前,下面我想想着手離子3完成一個功能在進行下一個功能

this.driveTo(); 

前完成

this.storage.set ("location", JSON.stringify(lsd_info)); 

我相信我應該使用。那麼( )。我想知道的是在繼續之前有一個簡單的解決方案來完成一個事件。

getLoc() { 
    let a = this.data.lsd; 
    let b = this.data.sec; 
    let c = this.data.twp; 
    let d = this.data.rng; 
    let e = this.data.mrd; 

    this.http.get('https://www.reversegeocoder.com/api/v1/PrivateID/lsd/' + a + '-' + b + '-' + c + '-' + d + ' ' + e) 
    .map(res => res.json()) 
    .subscribe (data => { 
     let lsd_info = { 
      latitude: data[0].response.lat, 
      longitude: data[0].response.lng, 
     }; 

     let lsd_error = {error: data[0].response.err}; 
     this.ErrorResponse = (JSON.stringify(data[0].response.err)); 
     this.ErrorText = this.ErrorResponse.replace('[','').replace(']',''); 
     this.storage.set ("location", JSON.stringify(lsd_info)); 

     //finish storage.set before proceeding 

     this.driveTo(); 

     }, 
      err => { 
       console.log('error'); 
      } 
    ); 
} 

driveTo() { 
    this.navCtrl.push(Drive); 
} 

還是有兩個功能,其中在功能出發

即getLoc(),然後driveTo()

+0

'this.storage.set do'是什麼? – echonax

+0

@echonax它會根據平臺在設備或本地存儲的SQLite數據庫或瀏覽器中的鍵值對中設置鍵值對,應用程序使用'ionic-native','Storage'運行,插入。 – rmalviya

+0

@echonax您可以查看離子存儲文檔[這裏](https://ionicframework.com/docs/storage/)。 – rmalviya

回答

2

你的猜測是正確的之前完成。您應該使用.then()來放置您的代碼,該代碼在離子型storage設置了鍵值對之後應運行,因爲ionic storage返回一個承諾,該鍵在鍵值已設置時解析。我修改了你的代碼,解決方案很簡單。

getLoc() { 
let a = this.data.lsd; 
let b = this.data.sec; 
let c = this.data.twp; 
let d = this.data.rng; 
let e = this.data.mrd; 

this.http.get('https://www.reversegeocoder.com/api/v1/PrivateID/lsd/' + a + 
'-' + b + '-' + c + '-' + d + ' ' + e) 
.map(res => res.json()) 
.subscribe (data => { 
    let lsd_info = { 
     latitude: data[0].response.lat, 
     longitude: data[0].response.lng, 
    }; 

    let lsd_error = {error: data[0].response.err}; 
    this.ErrorResponse = (JSON.stringify(data[0].response.err)); 
    this.ErrorText = this.ErrorResponse.replace('[','').replace(']',''); 
    this.storage.set ("location", JSON.stringify(lsd_info)).then(
    (value) => { 
     // storage.set finished 
     this.driveTo(); 
    }, 
    (reason) => { 
     console.log('Error occurred.'); 
     console.warn(reason); 
    }); 

    }, 
     err => { 
      console.log('error'); 
     } 
    ); 
} 

driveTo() { 
    this.navCtrl.push(Drive); 
} 
+0

謝謝。絆倒我的是.then()的(值)部分。我明白當我使用它與http獲取。但是我不確定這個例子中會發生什麼。 –

+0

'http.get()'返回'observable'而不是'promise'。參考[this](http://stackoverflow.com/questions/37364973/angular-promise-vs-observable)問題來了解差異。 – rmalviya