如何从angular4中读取resolve中的值

问题描述 投票:-1回答:1

我在使用角度4渲染视图之前使用resolve来加载数据。我遵循这个qazxsw poi并构建了我的应用程序,但我无法得到结果。

解决

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内调试时,我得到一个空对象,我期待值150 ngOnInit() { this.route.data.subscribe(success => { debugger; console.log(success) }) }

更新1 - 我的路由配置

enter image description here
angular
1个回答
2
投票

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

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

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

例如,这是我的:

  {
    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']);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.