我有一个应用程序如下。
我已经使用了解决方案,因为我想等到路由前收到数据。以上工作正常但是..
我想要的是是在第4部分中添加以下功能。
我想添加一些条件逻辑的原因是我在角度文档中看到它作为演示。 fetch before navigating
到目前为止,我有以下代码。
应用组件
const routes: Routes = [
{
path: '',
component: RegistrationComponent,
},
{
path: 'overview',
component: ConfirmationComponent,
resolve: {
data: RegistrationResolve
}
}
]
表单组件
export class RegistrationComponent implements OnInit {
constructor(
private router: Router,
private regService: RegistrationService,
private route: ActivatedRoute
){}
onSubmit(event: RegDetails){
this.handleView();
}
handleView(){
this.router.navigate(['/overview']);
}
}
概述组件
export class ConfirmationComponent implements OnInit {
constructor(
private router: Router,
private route: ActivatedRoute
) {}
ngOnInit(){
this.route.data
.subscribe(val => {
this.resolvedData = val["data"];
});
}
}
解析
export class RegistrationResolve implements Resolve<any> {
constructor(
private regService: RegistrationService,
private router: Router
) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.regService.postDummy('apple');
}
}
服务
export class RegistrationService {
constructor(private http: Http) {}
postDummy(data: string): Observable<any> {
return this.http
.post('https://demo4795542.mockable.io/test', data)
.map((response: Response) => response.json())
.catch ((error: any) => Observable.throw(error.json()));
}
}
注意: https://demo4795542.mockable.io/test只是24小时测试REST API。
所以查看代码我认为我需要在解决方案中处理响应。也许在决议中而不是在概述中订阅响应。
我正在考虑某些事情,并尝试过以下但不起作用
解决替换 - 尝试但失败
export class RegistrationResolve implements Resolve<any> {
tempData: any;
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.tempData = this.regService.postDummy('test')
.subscribe((data:any) =>
this.tempData = data["data"]
);
if (this.tempData !== undefined) {
console.log('Successful - routing to page');
return this.tempData;
} else {
console.log('Failed - not router anywhere');
this.router.navigate(['']);
return null;
}
}
}
任何帮助非常感谢。感谢
答案 0 :(得分:0)
在RegisterComponent的handleView方法而不是直接更改路由中,您可以向服务器发送http请求并获得响应。如果响应代码为200则为chnage route,否则显示错误
//**Below is the pseudo code**
handleView(){
RegisterationService.postDummy().subscribe(function(response){
if(response code is 200){
this.router.navigate(['/overview']);
} else{
show error on Ui
}
})
}
而不是在'概述路线'中使用解决方案而是使用canActive guard看 https://angular.io/docs/ts/latest/guide/router.html#!#guards