在我的服务中,我在本地存储中搜索变量:
SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE data_type='varbinary'
问题在于我有一个方法:
constructor(private storage: Storage) {
this.storage.get('value').then(
(val) => {
this.value = val;
},
() => {
this.value = 'no value';
});
}
此方法应返回值。但是价值并没有在开头设定。我怎么能这样做getVariable等到构造函数中的promise解决了?
答案 0 :(得分: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'];
});
}