2016-12-17 65 views
0

我正在嘗試將api注入到子狀態。我的狀態定義如下所示。在子狀態下注入解析

澄清一點。 「api」應該是名爲「root」的摘要中解決的值。我想在我的名爲「root.some2」的子狀態中使用該值。

{ 
    name: 'root', 
    abstract: true, 
    resolve: { 
    provide: 'api', 
    useFactory: (http) => http 
     .get(AppRoute.apiUrl) 
     .map((response: Response) => response.json()) 
     .toPromise(), 
    deps: [Http] 
    } 
}, 
{ 
    name: 'root.some2', 
    url: '/some2', 
    component: Something2Component, 
    resolve: [ 
    { 
     token: 'exercises', 
     resolveFn: (http, api) => http 
     .get(api._links.exercises.href) 
     .map((response: Response) => response.json()) 
     .toPromise(), 
     deps: [Http, 'api'] 
    } 
    ] 
} 

但是找不到api。我收到下面的錯誤。

Error: No provider for api! 
at NoProviderError.BaseError [as constructor] (errors.js:24) 
at NoProviderError.AbstractProviderError [as constructor] (reflective_errors.js:41) 
at new NoProviderError (reflective_errors.js:72) 
at ReflectiveInjector_._throwOrNull (reflective_injector.js:758) 
at ReflectiveInjector_._getByKeyDefault (reflective_injector.js:786) 
at ReflectiveInjector_._getByKey (reflective_injector.js:749) 
at ReflectiveInjector_.get (reflective_injector.js:558) 
at AppModuleInjector.NgModuleInjector.get (ng_module_factory.js:95) 
at UIInjectorImpl.getNative (resolveContext.js:178) 
at getDependency (resolveContext.js:145) 

任何有關錯誤的線索?

回答

1

使用下會導致孩子的狀態要定義的變量的API。

{ 
    name: 'root', 
    abstract: true, 
    resolve: { 
    api: [Http, (http) => http 
     .get(AppRoute.apiUrl) 
     .map((response: Response) => response.json()) 
     .toPromise()] 
    } 
}, 
{ 
    name: 'root.some2', 
    url: '/some2', 
    component: Something2Component, 
    resolve: { 
    token: 'exercises', 
    resolveFn: (http, api) => http 
     .get(api._links.exercises.href) 
     .map((response: Response) => response.json()) 
     .toPromise(), 
    deps: [Http, 'api'] 
    } 
} 
0

如果你需要一個服務在你解析方法yopu將需要一個函數的解析類insetad。 簡單的例子:

@Injectable() 
class MyResolver implements Resolve<MyObject> { 
    constructor(private backend: Backend) {} 

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any { 
     return WhateverPromiseOrObservableYouNeed; 
    } 
} 

在你的路由器:

​​
+0

但它不是服務。我只想使用在父狀態下解決的值(api)。 – user672009