gpt4 book ai didi

javascript - Angular - 如何在加载组件之前等待提供者获取请求完成?

转载 作者:行者123 更新时间:2023-12-02 22:04:32 24 4
gpt4 key购买 nike

我的程序使用了我的player.ts 文件中使用的全局变量。我将此播放器文件导入到侧边栏组件中,现在出现应用程序错误。问题是应用程序正在加载侧边栏组件,然后在player.ts 中完成获取请求。我首先在 app.module 中初始化player.ts 文件。如果在那里我可以提示应用程序在加载组件之前等待?我尝试使用await javascript关键字,但似乎所有组件和导入的文件都是从app.moudle异步加载的。

app.moudle.ts

 import { Player } from './player';
import { SidebarComponent } from './sidebar/sidebar.component';
@NgModule({
declarations: [
AppComponent,
SidebarComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [Player],
bootstrap: [AppComponent]
})

export class AppModule {

constructor(private player: Player) {
console.log("first console.log yeee");
this.processPlayer()
}
async processPlayer(){
let tester1 = await this.player.loadPlayer();
}
}

sidebar.component.ts

 import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Player } from '../player';

@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
projects
focussections
constructor(private router: Router, private player: Player) { }

ngOnInit() {
//get all the project to list on sidebar
this.projects = this.player.getAllProjects();
this.focussections = this.player.getAllSections4Project(this.focusID);
}

navigate2CreateTaskQuicky(){
let info = {typeID:0}
this.router.navigate(['/createtask', JSON.stringify(info)]);

}

}

玩家.ts

 @Injectable()
export class Player {
player : any
constructor(private http: HttpClient) {
this.ngOnInit();
}

async ngOnInit() {}

loadPlayer(){
return this.http.get(url)
.toPromise()
.then(
res => { // Success
this.player = res;
console.log("the player is fully loaded");
console.log(this.player);
}
);
}

getAllProjects(){
return this.player.projects;
}

getAllSections4Project(focusID){
let inboxSectionStack = [];
if(this.player){
for(let x = 0; x< this.player.sections.length; x++){
if(this.player.sections[x].project == focusID ){
inboxSectionStack.push(this.player.sections[x]);
}
}// loop through all tasks in player
}
return inboxSectionStack;
}

最佳答案

您必须使用APP_INITIALIZER提供者。其中是在呈现 AppComponent (以及任何其他组件)之前运行的服务:

应用程序模块:

providers: [
Player,
{
provide: APP_INITIALIZER,
useFactory: initApp,
multi: true,
deps: [ Player ]
}
]

然后你就可以 build 工厂了。确保工厂返回一个函数,该函数又返回一个 Promise:

export function initApp(player: Player) {
return () => this.player.loadPlayer()
}

如果您不关心 AppComponent 是否被渲染,但又不希望路由被解析,您可以将路由器配置中的 initialNavigation 标志设置为 false,并使用服务在 AppComponent 内部解析并路由到正确的路径

关于javascript - Angular - 如何在加载组件之前等待提供者获取请求完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59759427/

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