Angular 2-等待服务获取信息-设置变量后返回promise

时间:2019-06-14 08:23:42

标签: angular service promise

主要的应用组件正在从网络服务请求数据

然后在名为 coreService 的服务中设置一个变量,该变量将注入到各处以访问这些数据

问题是 others组件在app.component 获取信息之前就已加载,所以我遇到了大量未定义的问题

  • 我不会从coreService提取数据,否则将多次调用Web服务(尝试使用条件和pipe(),但它不起作用)

  • 我尝试使用AfterViewInit,但它可以间歇性地工作

app.component:

ngOnInit() {
    this.catalogService.getCampaign().then((data: any) =>
    {
        this.coreService.campaign=data;
    });
}

products.component :(路由器出口中加载的组件)

constructor(private coreService:CoreService)
{}

ngAfterViewInit()
{
    Promise.resolve(null).then(() => {   // to avoid value changed error b@#!t from angular
        if(this.coreService.campaign)
        {
                        ... // we should be here                
        }
        else
        {
            console.dir(this.coreService);
            throw "campaign not loaded yet";
        }
    });
}

我希望两个组件同步,也就是说,产品组件必须等待 coreService 获得其数据

此未定义链接在一起:

@Injectable({
  providedIn: 'root'
})
export class AppResolver implements Resolve<boolean> {

  constructor(private catalogService: CatalogService, private coreService:CoreService) { }

  public resolve(route: ActivatedRouteSnapshot): Promise<boolean> 
  {
    return this.catalogService.getCampaign(CoreService.CAMPAIGN_IDENTIFIER,null).then((data: any) => 
    {
        this.coreService.campaign=data;
        return true;
    })
    .then(function(result) : Promise<boolean>
    {
        // below this is undefined and throws an error
        //////////////////////////////////////////////
        return this.catalogService.getCampaign(CoreService.CAMPAIGN_IDENTIFIER,null).then((data: any) => {
            this.coreService.campaign=data;
            return true;
        });
    });
  }
}

1 个答案:

答案 0 :(得分:1)

您应该在Resolver中获取数据。

@Injectable({
  providedIn: 'root'
})
export class MyDataResolverService implements Resolve<boolean> {

  constructor(private catalogService: CatalogService, private coreService:CoreService) { }

  public resolve(): Promise<boolean> {
    return this.catalogService.getCampaign().then((data: any) => {
        this.coreService.campaign=data;
        return true;
    });
  }
}

然后在路由配置中使用解析器

...
  {
    path: '',
    component: AppComponent,
    resolve: {
      dataResolved: MyDataResolverService
    }
  }
....