gpt4 book ai didi

Angular - APP_INITIALIZER - Promise 与 Observable

转载 作者:太空狗 更新时间:2023-10-29 17:01:01 27 4
gpt4 key购买 nike

我有基于 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;
}
}

在应用程序的某处,我有一个名为 manageSettings() 的函数(目前它的代码并不重要),它要求来自 SettingsService 服务的数据是初始化。

事情是这样的——当我使用函数 load_two() 时,应用程序不会等到它完成:

app-root constructor
manageSettings()
loadSettings FINISH

当我使用函数 load_one() 时,它工作正常:

loadSettings FINISH
app-root constructor
manageSettings()

有人可以解释为什么会这样吗?

最佳答案

Angular 12 添加了对 Observable 的支持,因此如果您使用的是 Angular 12 或更新版本,这应该不再是一个问题。

load_one 有效而 load_two 无效的原因是 Angular 11 及更早版本仅等待 Promise;不是 Observable

这是 source :

if (this.appInits) {
for (let i = 0; i < this.appInits.length; i++) {
const initResult = this.appInits[i]();
if (isPromise(initResult)) {
asyncInitPromises.push(initResult);
}
}
}

在哪里isPromise定义如下:

export function isPromise<T = any>(obj: any): obj is Promise<T> {
// 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';
}

关于Angular - APP_INITIALIZER - Promise 与 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47422095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com