我正在使用角度7.0.4的项目。在我的组件中,我在declare var FB: any;
之前声明了一个像@Component({...})
这样的变量。
declare var FB: any;
@Component({
selector: 'app-login-modal',
templateUrl: './login-modal.component.html',
styleUrls: ['./login-modal.component.css']
})
export class LoginModalComponent implements OnInit {
private fbAuth;
constructor() { }
ngOnInit(): void {
if (FB) {
FB.getLoginStatus((r) => {
if (r.authResponse) {
this.fbAuth = r.authResponse;
console.log('Loggedin with facebook');
}
});
}
}
问题:有时它可以工作,但有时它会给出错误ERROR ReferenceError: FB is not defined
。我认为这是因为fb-sdk没有加载或加载但是过了一段时间。
我的问题:有没有办法检查typescript是否定义变量?
提前致谢
首先,您应该弄清楚为什么没有定义FB
。 ;)
你声明它的方式假定它是在全局范围内声明的,但如果它不是那么JS will raise an error in strict mode。你可以改为将它声明为Window
对象的成员,它可以让你检查它是否定义而没有JS引发错误:
// in a `global.d.ts` file:
interface Window {
FB?: any;
}
ngOnInit() {
if (window.FB) {
// ...
}
}