【发布时间】:2017-11-04 09:35:11
【问题描述】:
我有一个应用如下。
- 用户填写表单(路由为“”)
- 提交表单
- 数据被发送到 REST api
- 数据已接收 - 在良好的响应 (200) 上,页面被路由到包含响应的概览页面。 (路线是“概述”)在 (400) 上,它目前静默失败。
我为此使用了解析,因为我想等到收到数据后再进行路由。以上工作正常,但是..
我想要的是在第 4 部分中添加以下功能。
- 当收到 400 或非 200 错误时,我想显示错误并确保路由为“”。
我想在其中添加一些条件逻辑的原因是我将其视为 angular 文档中的演示。 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;
}
}
}
非常感谢任何帮助。谢谢
【问题讨论】:
标签: javascript angular typescript angular2-routing resolve