2017-04-11 64 views
0

休息,在我服務,我尋找我的localStorage一個變量:多久之前等待一個承諾執行代碼

constructor(private storage: Storage) { 

    this.storage.get('value').then(
       (val) => { 
        this.value = val; 
       }, 
       () => { 
        this.value = 'no value'; 
       }); 
    } 

的問題是,我有一個方法:

getVariable(){ 
    return this.value; 
} 

這種方法應該返回值。但是價值並不是一開始就設定的。我該怎麼做,getVariable等到構造函數解析的承諾是?

+0

如果您可以爲您的問題提供一些背景信息會很有幫助EM。如果您將此值用於字符串插值,則可以等待更改檢測觸發。 –

回答

0

您可以使用路由解析器或依靠OnInit接口。 如果您絕對需要等待承諾解決,然後使用解析器。

下面是一個例子:

@Injectable() 
export class MyResolver implements Resolve<any> { 

    constructor(
    private storage: MyStorageService,) { 
    } 

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> { 

    return this.storage.get('value').then(
      (val) => { 
       return val; 
      }, 
      () => { 
       return 'no value'; 
      }); 
    } 
} 

在你的路由配置,鏈接你的路線,分解如下:

{ 
    path: 'myyPath', 
    component: MyComponent, 
    resolve: { 
     myResolvedValue: MyResolver // myResolvedValue is the key under which you'll be able to retrieved the resolved value. You can put whichever key you want 
    }, 
    }, 

最後,綁定路由數據的變化到您的組件(注意,您必須實現OnInit):

constructor(private route: ActivatedRoute) { 

} 

ngOnInit(): void { 
    this.route.data.subscribe(data => { 
     this.value= data['myResolvedValue']; 
    }); 
    } 
相關問題