解析器Angular 6

时间:2018-08-15 20:59:59

标签: angular typescript

我正在为Angular 6应用程序的路由创建解析器。

当前,我调用API并将数据返回给组件,以便它可以在组件的模板中呈现数据。

foo.resolver.ts

@Injectable()
export class FooResolver implements Resolve<any> {

  constructor(private fooService: FooService) {}

  resolve(route: ActivatedRouteSnapshot) {   
    return this.fooService.getById(route.paramMap.get('id'));
  }
}

foo.component.ts

export class FooComponent implements OnInit {

  fooObj: any = {};

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {    
    this.fooObj = this.route.snapshot.data.fooObject;    
  }
}

但是,一旦getById完成并将自定义对象返回给foo.component.ts类,我就需要更改当前的实现以对另一个API进行子调用。我试图编辑resolve函数以反映此要求。

resolve(route: ActivatedRouteSnapshot) {   

    return this.FooService.getById(route.paramMap.get('id')).pipe(map(result => {

        this.fooService.getType().subscribe(results => {

            result.type = this.getObject(results, result.typeId);

        });

        return result;
    }));

private getObject(collection: any, id: number): any {
    return collection.find(e => e.id == id);
}

但是,控制台出现错误。关于无法读取未定义的属性“名称”。我不认为我会从第二版的resolve函数中重提一个完成的Observable。

1 个答案:

答案 0 :(得分:2)

代码应为

return this.FooService.getById(route.paramMap.get('id')).pipe(
  switchMap(result => 
    this.fooService.getType().pipe(
      map(results => {
        result.type = this.getObject(results, result.typeId);
        return result;
      })
    )
  )
);

否则,路由器在第一个可观察到的对象发出后立即将结果提供给组件,而无需等待第二个。