我正在尝试找到一种方法来处理是否在组件模板中引发了未定义的错误。发生这种情况时,应用程序将崩溃,所需的解决方案是导航到“应用程序错误”组件或将错误的组件替换为“应用程序错误”组件,以使应用程序保持运行状态。
答案 0 :(得分:0)
您可以在代码上使用try / catch块,但是在较大的应用程序中进行管理可能很繁琐。相反,您可以通过从@ angular / core扩展ErrorHandler来创建自己的错误处理逻辑。
像这样的东西
import { ErrorHandler } from '@angular/core';
@Injectable()
export class YourErrorHandler implements ErrorHandler {
handleError(error) {
// your custom error handling logic
}
}
然后,像这样将其添加到您的根模块中;
@NgModule({
providers: [{provide: ErrorHandler, useClass: GlobalErrorHandler}]
})
答案 1 :(得分:0)
没有一种通用方法可以将所有undefined
捕获在一个地方。
仅当您编写的代码不安全或/和不够清洁时才会发生此错误。
一些好的做法领域:
const myVar: string = null;
class MyClass {
public myAttr: string = null
}
// matches not null & not undefined
if (newVal != null) {
myVar = newVal;
}
// matches only not undefined
if (newVal !== undefined) {
myVar = newVal;
}
// matches only not null
if (newVal !== null) {
myVar = newVal
}