如何在渲染组件之前使Angular2等待一个promise
发布时间:2020-12-17 07:11:34 所属栏目:安全 来源:网络整理
导读:第一:是的,我事先用Google搜索过,而 solution出现的对我来说并不适用. 上下文 我有一个调用服务的Angular 2组件,并且在收到响应后需要执行一些数据操作: ngOnInit () { myService.getData() .then((data) = { this.myData = /* manipulate data */ ; }) .c
第一:是的,我事先用Google搜索过,而
solution出现的对我来说并不适用.
上下文 我有一个调用服务的Angular 2组件,并且在收到响应后需要执行一些数据操作: ngOnInit () { myService.getData() .then((data) => { this.myData = /* manipulate data */ ; }) .catch(console.error); } 在其模板中,该数据将传递给子组件: <child-component [myData]="myData"></child-component> 这导致一个错误,即孩子将myData视为未定义.上面发布的谷歌搜索结果谈到使用Resolver,但这对我不起作用. 当我创建一个新的解析器时: import { Injectable } from '@angular/core'; import { Resolve,ActivatedRouteSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { MyService } from './my.service'; @Injectable() export class MyResolver implements Resolve<any> { constructor(private myService: MyService) {} resolve (route: ActivatedRouteSnapshot): Observable<any> { return Observable.from(this.myService.getData()); } } app.routing.ts const appRoutes: Routes = [ { path: 'my-component',component: MyComponent,resolve: { myData: MyDataResolver } } ]; export const routing = RouterModule.forRoot(appRoutes); 我收到一个错误,即没有MyDataResolver的提供程序.当我将MyDataResolver添加到app.component.ts中的providers属性时,情况仍然如此: @Component({ selector: 'my-app',templateUrl: 'app/app.component.html',providers: [ MyService,MyResolver ] }) 使用此接口的界面是否已更改? 解决方法
路由器支持从resolve()返回的promise或observable.
另见 https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html 这应该做你想要的: @Injectable() export class MyResolver implements Resolve<any> { constructor(private myService: MyService) {} resolve (route: ActivatedRouteSnapshot): Promise<any> { return this.myService.getData(); } } 另见https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读