Ton*_*ony 14 typescript angular
我有基于Angular v4的应用程序.场景很简单 - 我需要在应用程序启动之前从服务器加载一些设置.为此,我使用APP_INITIALIZER:
{
provide: APP_INITIALIZER,
useFactory: init,
deps: [SettingsService],
multi: true
}
export function init(config: SettingsService) {
return () => config.load_one();
}
//import declarations
@Injectable()
export class SettingsService {
constructor(private http: HttpClient) { }
load_one(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
this.http.get('url').subscribe(value => {
console.log('loadSettings FINISH');
resolve(true);
});
});
}
load_two(): Observable<any> {
const promise = this.http.get('url');
promise.subscribe(value => {
console.log('loadSettings FINISH');
});
return promise;
}
}
Run Code Online (Sandbox Code Playgroud)
在应用程序的某个地方,我有一个被调用的函数manageSettings()(它的代码目前无关紧要),这需要SettingsService初始化服务中的数据.
事情就是这样 - 当我使用该功能时load_two(),应用程序不会等到它完成:
app-root constructor
manageSettings()
loadSettings FINISH
Run Code Online (Sandbox Code Playgroud)
当我使用该功能时,load_one()它工作正常:
loadSettings FINISH
app-root constructor
manageSettings()
Run Code Online (Sandbox Code Playgroud)
谁能解释为什么会这样?
Kir*_*kin 20
原因load_one有用而且load_two不简单:Angular只会等待Promises; 不是Observable.
在查看文档,博客文章,教程等时,很难找到关于是否支持返回s 的明确答案.很明显它确实支持s - 例如:APP_INITIALIZERObservablePromise
如果函数返回promise直到promise解析,Angular将延迟初始化.
为了确保,您实际上可以看到Angular 代码正在做什么:
if (isPromise(initResult)) {
asyncInitPromises.push(initResult);
}
Run Code Online (Sandbox Code Playgroud)
在哪里isPromise定义如下:
export function isPromise(obj: any): obj is Promise<any> {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
Run Code Online (Sandbox Code Playgroud)
有没有引用Observable的APP_INITIALIZER代码; 就是Promises.
| 归档时间: |
|
| 查看次数: |
3876 次 |
| 最近记录: |