如何捕获 templateUrl 加载错误

How to catch a templateUrl load error

假设无法传递对组件模板的请求(状态代码 400 等),是否有办法捕获错误以采取措施(重定向等) ..)

谢谢。

目前我不知道在 templateUrl 中进行捕获的方法。

作为解决方法,我们可以做的是发出 head 请求以检查文件是否存在。

因此,您的组件将如下所示:

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() {
  }
}

我知道这不是最佳解决方案。但目前我认为这是一个简单的解决方法,可以让您在模板文件不存在的情况下进行回退。

据我所知,目前 (beta.2) 没有这样的机制。

你可以查看获取模板的normalizeTemplate方法的source code,我认为如果发生错误没有办法插入一些逻辑。

使用 angular2 的新解析器,您可以在加载模板之前预取数据。我想您可以使用相同的机制来预取模板,即使您只是将其丢弃。如果请求有问题,您可以在 catch 块中重定向。

https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard 上有很好的信息和一个很好的示例,我将其包含在下面以防 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;
      }
    });
  }
}

我知道这个问题很老了,但今天我们有更好的解决方案。

Angular 提供了一个名为 ResourceLoader 的 class,您可以扩展并创建自己的实现来覆盖基本行为。

我创建了一个从 ResourceLoader 扩展的 CustomResourceLoader 以在 templateUrl 请求中插入令牌,因为我的页面是由服务器提供的。

因此,您可以使用它来捕获错误并做出您想要的结果。

您可以在 this link, and a example of how extend correctly 上看到 ResourceLoader 的 angular 实现。