如何在root组件中获取params? (app.component.ts)
我有这样的app.component.ts(我正在使用Angular / Cli):
...
import {Transition} from "@uirouter/angular";
...
export class AppComponent {
id: any;
constructor(private trans: Transition) {
this.id = trans.params().someId;
}
}
但我明白了:
ERROR Error: No provider for Transition!
但是如果我在任何内部组件(有路由)中使用相同的逻辑 - 一切都很好。我做错了什么?
另外!
我正在使用ngx-restangular
。我在app.module.ts
:
// Function for settting the default restangular configuration
export function RestangularConfigFactory (RestangularProvider, authService) {
RestangularProvider.setBaseUrl('http://api.test.com/v1');
// This function must return observable
var refreshAccesstoken = function () {
// Here you can make action before repeated request
return authService.functionForTokenUpdate();
};
RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
if (response.status === 403) {
/*Here somehow I need to get route params too, is it possible, and how?*/
refreshAccesstoken()
.switchMap(refreshAccesstokenResponse => {
//If you want to change request or make with it some actions and give the request to the repeatRequest func.
//Or you can live it empty and request will be the same.
// update Authorization header
response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)
return response.repeatRequest(response.request);
})
.subscribe(
res => responseHandler(res),
err => subject.error(err)
);
return false; // error handled
}
return true; // error not handled
});
}
// AppModule is the main entry point into Angular2 bootstraping process
@NgModule({
bootstrap: [ AppComponent ],
imports: [
// Importing RestangularModule and making default configs for restanglar
RestangularModule.forRoot([authService], RestangularConfigFactory),
],
})
我怎样才能到达路线参数?
答案 0 :(得分:2)
如果您目前拥有index.html:
<root-component></root-component> <!-- has a ui-view inside it -->
和
bootstrap: RootComponent
您可以切换到引导UIView:
<ui-view></ui-view>
和
bootstrap: UIView
然后路由到您的根组件
const rootState = { component: RootComponent }
然后您的根组件将能够注入初始Transition
请参阅示例应用程序以获取示例:
class RootComponent {
constructor(router: UIRouter) {
this.subscription = router.globals.start$.subscribe((trans: Transition) => console.log(trans)))
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
如果您尝试为初始转换执行某些操作,请在转换挂钩中执行此操作
function configFn(router: UIRouter) {
router.transitionService.onStart({}, function(trans: Transition) {
if (trans.$id === 0) {
return somepromise; // Allows async, etc
}
}
}