Assuming that the request for the template of a component, can't be delivered (status code 400, etc..), is there a way to catch the error in order to take an action (redirect, etc...)
Thanks.
I know that the question is very old, but today we have a better solution.
Angular provides a class called ResourceLoader
that you can extend and create your own implementation overriding the base behavior.
I'm created a CustomResourceLoader
that extends from ResourceLoader
to insert tokens on templateUrl
request, because my pages are provided by a server.
So, you can use this to catch errors and make what you want.
You can see the angular implementation of ResourceLoader
on this link, and a example of how extend correctly here.
Currently I am not aware of a way to do a catch in the templateUrl
.
What we can do, as a workaround, is making an head
request to check if the file exists.
So, your component would look something like this:
import {Component, View} from 'angular2/angular2';
let hasTemplate = function(template: string) {
var http = new XMLHttpRequest();
http.open('HEAD', template, false);
http.send();
return (http.status===200) ? template : 'error.html';
}
@Component({
selector: 'your-component'
})
@View({
templateUrl: hasTemplate('your-template.html')
})
export class YourComponent {
constructor() {
}
}
I know this is not a optimum solution. But for the time being I think its an easy workaround that will allow you to make a fallback in case the template file isn't present.
AFAIK there is currently (beta.2) no such mechanism.
You can check the source code of the normalizeTemplate
method that fetches the template, I don't think there is a way to plug some logic if an error happens.
Using angular2's new resolver you can pre-fetch data before loading the template. I suppose you can use the same mechanism to prefetch the template, even if you just throw it away. In the catch block you can redirect if there is some problem with the request.
There is good information and a nice example at https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard, which I included below in case something happens to the link.
import { Injectable } from '@angular/core';
import { Router, Resolve,
ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Crisis, CrisisService } from './crisis.service';
@Injectable()
export class CrisisDetailResolve implements Resolve<Crisis> {
constructor(private cs: CrisisService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
let id = +route.params['id'];
return this.cs.getCrisis(id).then(crisis => {
if (crisis) {
return crisis;
} else { // id not found
this.router.navigate(['/crisis-center']);
return false;
}
});
}
}
http
interceptor, which could help to find there is an error while fetching anything overhttp
protocol..$rotueChangeError
event in Angular1?