微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在渲染组件之前使Angular2等待一个promise

第一:是的,我事先用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐