当数据服务控制台记录数据正常时,Angular2解析器返回undefined

时间:2017-03-20 18:41:55

标签: angular http asynchronous resolve resolver

我试图通过使用angular2的解析器在显示组件之前预取数据。

所以在我的data.service.ts中: 我有一个检索员工详细信息的函数:

  getEmployee(id:string) {
      let headers = new Headers();
      this.createAuthorizationHeader(headers);
      this.employeeUrl = 'someurl/property?'+'employee_number='+id;
      return this._http.get(this.employeeUrl, {headers})
        .map(resp => resp.json())
        .do(data => console.log('employee: ' +  JSON.stringify(data)))

//this returns a json log in console. 

在我的employee-detail-resolver.service.ts文件中,我设置了一个这样的解析器:

@Injectable()
export class EmployeeDetailResolver implements Resolve<IEmployee>{
  employee: IEmployee;

  constructor( private _dataService: DataService, private router: Router ) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<IEmployee> {
    console.log('returning resolved data');
    let id = route.params['id'];
    return this._dataService.getEmployee(id)
      .map(employee => {
        if(employee) {
        return employee;
      } else {
        this.router.navigate(['/employees']);
        return null;
      }
    });

}

}

我尝试从employee-detail.component.ts文件中的解析器获取数据,如下所示:

export class EmployeeDetailComponent implements OnInit {
  busy: Subscription;
  employee: IEmployee;
  id: string;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private _dataService: DataService
              ) {

    }


  ngOnInit() {
    this.route.data
      .subscribe((data: {employee: IEmployee}) => {
        this.employee = data.employee;
      })
     console.log("testing employee detail:", this.route.snapshot.data['data']);
  // this logs undefined in the console
  }

  onBack(): void {
    this.router.navigate(['/employees']);
  }
}

我知道我正在准确地获取数据,因为我在控制台中看到它,并且我的模板带有* ngIf =“employee”加载时没有数据。我不明白为什么我的组件返回未定义的值..

我的路由模块如下所示:

const APP_ROUTES: Routes = [
    {path: 'employee/:id', component: EmployeeDetailComponent,
      resolve: {
       employee: EmployeeDetailResolver
      }
    },
    {path: 'employees', component: EmployeesListComponent},
    {path: '', redirectTo: '/employees', pathMatch: 'full' }
];

export const Routing = RouterModule.forRoot(APP_ROUTES, {useHash: true});

我在app.module.ts中声明它是一个提供者:

  providers: [ DataService, EmployeeDetailResolver ],

有人可以帮我理解我做错了吗?

FIX: 在employee-detail.component.ts中 我改为

  ngOnInit() {
    this.employee = this.route.snapshot.data['employee'][0];
    console.log("working?",this.employee[0]);
  }

现在每次点击都会显示数据! 这是快照!!!

1 个答案:

答案 0 :(得分:3)

依赖于来自异步调用的数据的代码需要在数据到达时调用的回调中执行:

this.route.data
  .subscribe((data: {employee: IEmployee}) => {
    this.employee = data.employee;
    console.log("testing employee detail:", data['data']);

  })
  // code here is executed before async data was received