Angular中出现ERROR ReferenceError: bootstrap is not defined问题求助
解决Angular中
ReferenceError: bootstrap is not defined问题 核心原因
你启用了SSR(服务端渲染/预渲染),而Bootstrap是依赖浏览器window对象的前端库。在服务器渲染阶段,代码会在无浏览器环境的Node.js中执行,此时bootstrap全局对象不存在,因此抛出错误——虽然浏览器控制台能看到bootstrap,但服务器端渲染的报错已经提前触发。
解决方案
1. 仅在浏览器环境中调用Bootstrap
使用Angular提供的isPlatformBrowser工具,确保只有在浏览器环境下才执行Bootstrap相关逻辑:
修改组件代码如下:
import { Component, OnInit, AfterViewInit, ElementRef, Renderer2, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; import { User } from '../../models/user'; import { UserService } from '../../services/service-user/user.service'; import { ModalService } from '../../services/service-modal/modal.service'; import { LoginResponse } from '../../models/login-response'; declare var bootstrap: any; @Component({ selector: 'app-modal-login', templateUrl: './modal-login.component.html', styleUrl: './modal-login.component.css' }) export class ModalLoginComponent implements OnInit, AfterViewInit { user: User = new User(); private isBrowser: boolean; constructor( private userService: UserService, private renderer: Renderer2, private el: ElementRef, private modalService: ModalService, @Inject(PLATFORM_ID) private platformId: Object ) { this.isBrowser = isPlatformBrowser(this.platformId); } ngOnInit(): void {} ngAfterViewInit(): void { if (!this.isBrowser) return; const modalElement = this.el.nativeElement.querySelector('#loginModal'); this.renderer.listen(modalElement, 'hide.bs.modal', () => { this.clearForm(); }); this.modalService.showModal$.subscribe(show => { if (show === 'open') { this.openModal(); } else if (show === 'close') { this.closeModal(); } }); } login(): void { this.userService.loginUser(this.user).subscribe({ next: (response: LoginResponse) => { console.log(response), localStorage.setItem('token', response.token), this.closeModal() }, error: (error) => console.log(error) }); } openModal(): void { if (!this.isBrowser) return; const modalElement = this.el.nativeElement.querySelector('#loginModal'); const modal = bootstrap.Modal.getInstance(modalElement); modal.show() } closeModal(): void { if (!this.isBrowser) return; const modalElement = this.el.nativeElement.querySelector('#loginModal'); const modal = bootstrap.Modal.getInstance(modalElement); modal.hide(); } clearForm(): void { this.user = new User(); } }
2. 修复订阅逻辑错误
原代码中this.modalService.showModal$.subscribe的判断逻辑存在问题:if ('open')是判断字符串字面量的真值,永远为true,会导致无论show是什么值都会执行openModal()。已在上面的代码中修正为判断show变量的实际值。
额外说明
你的angular.json中Bootstrap的引入配置是正确的,无需修改。
内容的提问来源于stack exchange,提问作者MrLiu
相关产品推荐
相关产品推荐

