父组件中的服务在子组件之后运行

时间:2018-05-09 10:56:08

标签: angular typescript

我有一个在ngInit函数上运行服务的父组件。然后我使用从子组件服务接收的数据。但似乎子组件首先运行,之后,父组件从服务接收数据。 如何首先从服务中接收数据?

父组件:

export class ReportComponent implements OnInit {

    public report: Report = new Report();

    constructor(private reportService: ReportService) {}

    ngOnInit() {
        //get report detail data from API ............
        this.reportService.getReport('1')
      .subscribe(
        (data: any) => {
            this.report.serialNum_used_probe = data.serialNum_used_probe;
            this.report.created_datetime = data.created_datetime;
        }
      );

}

2 个答案:

答案 0 :(得分:1)

我已经完成了这些步骤:

1)创建一个ReportResolver类:

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

  constructor(private reportService: ReportService){}

  resolve(route: ActivatedRouteSnapshot, rstate: RouterStateSnapshot):   Observable<any>{
    return this.reportService.getReport(route.paramMap.get('pk'));
  }
}

2)将此类添加到路由列表:

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'report/:pk', component: ReportComponent, resolve: {reportData: ReportResolver} }
];

3)在主要组件中调用http函数:

export class ReportComponent implements OnInit {

    public report: Report;
    constructor(private route: ActivatedRoute,
                private reportService: ReportService) {
    }

    ngOnInit() {

        this.route.data.map(data => data.reportData).subscribe(
          (data: any) => {
             this.report = new Report();
             this.report.serialNum_used_probe = data.serialNum_used_probe;
             this.report.created_datetime = data.created_datetime;
       });

  }
}

这对我有用。

答案 1 :(得分:0)

我假设您在子组件上使用类似* ngIf或@Input的内容来从父组件传输数据。

考虑不要在API请求之后初始化变量并创建实例:

export class ReportComponent implements OnInit {

    public report: Report;

    constructor(private reportService: ReportService) { }

    ngOnInit() {
        //get report detail data from API ............
        this.reportService.getReport('1')
            .subscribe(
                (data: any) => {
                    this.report = new Report();
                    this.report.serialNum_used_probe = data.serialNum_used_probe;
                    this.report.created_datetime = data.created_datetime;
                }
            );
    }
}