Javascript 等待承诺,然后将结果作为输入参数
我有两个组件:父组件和子组件 父级正在解析构造函数中的承诺,子级正在将承诺的结果作为@Input参数重新发布 除了afterViewCheck和afterContentCheck,孩子在生活中没有收到承诺的结果,我想避免这些 我还希望避免在behaviorSubject或类似的东西中包含共享数据的共享服务 所以问题是,我可以在使用承诺的结果作为输入参数构建模板之前等待承诺吗 家长:Javascript 等待承诺,然后将结果作为输入参数,javascript,angular,typescript,firebase,rxjs,Javascript,Angular,Typescript,Firebase,Rxjs,我有两个组件:父组件和子组件 父级正在解析构造函数中的承诺,子级正在将承诺的结果作为@Input参数重新发布 除了afterViewCheck和afterContentCheck,孩子在生活中没有收到承诺的结果,我想避免这些 我还希望避免在behaviorSubject或类似的东西中包含共享数据的共享服务 所以问题是,我可以在使用承诺的结果作为输入参数构建模板之前等待承诺吗 家长: // html: <app-chil [brands]="brands"></> bra
// html: <app-chil [brands]="brands"></>
brands: Brand[] = []
constructor() {
this.getBrands()
}
async getBrands() {
this.brands = await new Promise<Brand[]>(resolve =>
this.equipmentService.getBrands().subscribe(brands => resolve(brands)))
}
使用setter,您不需要使用任何生命周期挂钩及其清洁剂
brands: Brand[] = [];
constructor() {
this.getBrands()
}
async getBrands() {
this.brands = await new Promise<Brand[]>(resolve =>
this.equipmentService.getBrands().subscribe(brands => resolve(brands)))
}
从promise中创建observable并将该observable传递给子级,然后使用异步管道的简单插值 下面是一个例子。阅读它并使其适应您的应用程序,它已按原样进行测试 儿童:
@Input() brands: Brand[] = []
constructor() { }
ngAfterViewInit() {
console.log(this.brands) // receive brands here
}
private _brands: Brand[] = [];
@Input() set brands(data: Brand[]) {
this._brands = data;
console.log(data);
}
constructor() { }
从“@angular/core”导入{Component,Input};
从“rxjs”导入{Observable};
@组成部分{
选择器:“你好”,
模板:`Hello{{name | async}}!`,
样式:[`h1{font-family:Lato;}`]
}
导出类HelloComponent{
@输入名称:可观察;
}
家长:
从'@angular/core'导入{Component};
从'rxjs'导入{of};
/*从'rxjs'导入{from}//导入“from”将您的承诺转换为可观察的*/
@组成部分{
选择器:“我的应用程序”,
模板:``,
样式URL:['./app.component.css']
}
导出类AppComponent{
name=of角;//name=fromyourPromise
}
您可以在构造函数中执行this.equipmentService.getBrands.subscribebebBrands=>this.brands=brands…您应该在输入上使用setter,这样您就可以确保数据实际上正在传递给子级。输入不会被更新,除非参考变更是您试图从promise中使可观察到的,并将可观察到的传递给子对象,然后使用简单的插值和异步管道?{{received$| async}}@hereticsmonkey子组件是标准的,由许多家长共享,所以我不能这样做。