如何从angular4

时间:2018-01-24 18:21:27

标签: angular

我在使用angular4呈现视图之前使用resolve来加载数据。 我遵循了这个stack overflow并构建了我的应用程序,但我无法得到结果。

分解器

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class Books implements Resolve<any> {
  constructor() { }

  resolve(route: ActivatedRouteSnapshot) {
    return new Observable(observer => {
      setTimeout(function () {
        observer.next(150);
        observer.complete();
      }, 1000);
    });
  }
}

我的组件

ngOnInit() {
    this.route.data.subscribe(success => {
      debugger;
      console.log(success)
    })
  }

当我在ngOninit中调试时,我得到一个空对象,我期待值150 enter image description here

更新1 - 我的路由配置

export const appRoutes: Routes = [
    {
        path: '',
        component: AppComponent,
        resolve: {
            users: Books
        }
    }
];

1 个答案:

答案 0 :(得分:2)

我假设你有一个定义使用该解析器的路径?例如,这是我的一个:

  {
    path: ':id',
    component: ProductDetailComponent,
    resolve: { product: ProductResolver }
  },

然后使用上面解决方案中指定的名称读取解析器数据。

例如,这是我的:

ngOnInit(): void {
    // Watch for changes to the resolve data
    this.route.data.subscribe(data => {
         this.onProductRetrieved(data['product']);
    });
}

看来你的应该是这样的:

ngOnInit() {
    this.route.data.subscribe(success => {
      debugger;
      console.log(success[yourNameHere]);
    })
  }