Angular中Observable订阅在一个组件生效另一个无响应的原因?
问题:Angular中ViewTask组件订阅Observable无响应,仅App组件生效
我的Angular项目包含App、Column(内含Task组件列表)、ViewTask(点击Task时显示)三个组件,还有一个带Observable的UiService服务类。现在在App和ViewTask两个组件中订阅同一个Observable,但只有App的订阅回调正常工作,ViewTask的订阅完全没反应,控制台应该打印两次task对象才对,这是为什么?
相关代码
UiService 服务类
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UiService { constructor() { } private taskDisplaySubject = new Subject<any>(); taskDisplay$ = this.taskDisplaySubject.asObservable(); showTask(taskData: any) { this.taskDisplaySubject.next(taskData); console.log(`showTask was called`); } }
Column组件
HTML模板
<div class="column"> <header class="column-header"> <h3 class="column-title"> {{ columnName }} <span class="num-of-tasks">({{ numOfTasks }})</span> </h3> </header> <div class="tasks-list"> <app-task *ngFor="let task of tasks" [task]="task" [columnOfTask]="columnName" (click)="onTaskClick(task)" ></app-task> </div> </div>
TypeScript代码
import { Component, Input, OnInit } from '@angular/core'; import { HttpService } from 'src/app/services/http.service'; import { UiService } from 'src/app/services/ui.service'; @Component({ selector: 'app-column', templateUrl: './column.component.html', styleUrls: ['./column.component.css'], }) export class ColumnComponent implements OnInit { constructor(private http: HttpService, private uiService: UiService) {} ngOnInit(): void { } onTaskClick(taskObject: any) { this.uiService.showTask(taskObject); } }
App组件
TypeScript代码
import { Component, Output } from '@angular/core'; import { UiService } from './services/ui.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'task-management-frontend'; @Output() showBoardsModal: boolean = false; showDeleteModal: Boolean = false; deleteModalType!: string; showSidebar = false; showTask = false; constructor(private uiService: UiService) {} ngOnInit(): void { this.uiService.taskDisplay$.subscribe((taskData) => { this.showTask = true; console.log(taskData); }) this.uiService.toggleEmitted$.subscribe(isShown => { this.showSidebar = isShown; }) } }
HTML模板
<div class="container"> <aside *ngIf="showSidebar"> <app-sidebar></app-sidebar> </aside> <app-titlebar (showBoardsModal)="onToggleBoardsModal()" (showDeleteModal)="onToggleDeleteModal($event)" [displayBoardsModal]="showBoardsModal" [ngClass]="{ 'enlarge-titlebar': !showSidebar }" ></app-titlebar> <div class="main" [ngClass]="{ 'enlarge-main': !showSidebar }"> <router-outlet></router-outlet> </div> <app-view-task *ngIf="showTask"></app-view-task> <app-boards-modal (hideModalEvent)="onToggleBoardsModal()" *ngIf="showBoardsModal" ></app-boards-modal> <app-delete-modal *ngIf="showDeleteModal" (hideDeleteModal)="onToggleDeleteModal()" [deleteModalType]="deleteModalType" ></app-delete-modal> <button class="show-sidebar-btn" *ngIf="!showSidebar" (click)="displaySidebar()"> <svg width="16" height="11" xmlns="http://www.w3.org/2000/svg"> <path d="M15.815 4.434A9.055 9.055 0 0 0 8 0 9.055 9.055 0 0 0 .185 4.434a1.333 1.333 0 0 0 0 1.354A9.055 9.055 0 0 0 8 10.222c3.33 0 6.25-1.777 7.815-4.434a1.333 1.333 0 0 0 0-1.354ZM8 8.89A3.776 3.776 0 0 1 4.222 5.11 3.776 3.776 0 0 1 8 1.333a3.776 3.776 0 0 1 3.778 3.778A3.776 3.776 0 0 1 8 8.89Zm2.889-3.778a2.889 2.889 0 1 1-5.438-1.36 1.19 1.19 0 1 0 1.19-1.189H6.64a2.889 2.889 0 0 1 4.25 2.549Z" fill="#FFF" /> </svg> </button> </div>
ViewTask组件
TypeScript代码
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { HttpService } from 'src/app/services/http.service'; import { UiService } from 'src/app/services/ui.service'; @Component({ selector: 'app-view-task', templateUrl: './view-task.component.html', styleUrls: ['./view-task.component.css'], }) export class ViewTaskComponent implements OnInit { taskId!: string; taskTitle!: string; taskDescription!: string; currentColumn!: string; columns!: any[]; columnId!: string; boardId!: string; subtasks = []; numOfSubtasks!: number; numOfSubtasksDone = 0; showColumnDropdown: boolean = false; showEditDropdown: boolean = false; constructor( private route: ActivatedRoute, private http: HttpService, private ui: UiService ) {} ngOnInit(): void { this.ui.taskDisplay$.subscribe((taskData) => { console.log(taskData); }); this.boardId = this.ui.boardId; } }
问题原因
核心问题出在组件初始化时机和Subject的特性上:
- 组件创建顺序:点击Task时,
showTask方法触发taskDisplaySubject.next()发送数据,但此时ViewTask组件还没被创建——App组件中showTask初始值为false,<app-view-task *ngIf="showTask"></app-view-task>不会渲染。只有当App的订阅回调执行后,showTask才被设为true,ViewTask组件才开始初始化。 - Subject的特性:
Subject只会把数据发送给订阅发生时已经存在的订阅者。也就是说,在next()调用之后才订阅的观察者,收不到之前发送的数据。
简单流程:点击Task→发送数据→App订阅收到数据→设置showTask=true→ViewTask开始创建并订阅→此时数据已经发送完毕,ViewTask的订阅自然收不到。
解决方案
方式一:改用BehaviorSubject(推荐)
BehaviorSubject会保留最新的一次数据,新订阅的观察者会立即收到这个最新值。修改UiService:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UiService { constructor() { } // 初始化时可传入null或默认值 private taskDisplaySubject = new BehaviorSubject<any>(null); taskDisplay$ = this.taskDisplaySubject.asObservable(); showTask(taskData: any) { this.taskDisplaySubject.next(taskData); console.log(`showTask was called`); } }
这样ViewTask组件初始化订阅时,会立即收到最新的taskData。
方式二:调整组件渲染逻辑(不推荐)
如果不想修改Subject类型,可以先创建ViewTask组件再发送数据,但这种方式容易引入时序问题。比如在App组件中先设置showTask=true,等待ViewTask初始化完成后再发送数据,但需要借助setTimeout或AfterViewInit生命周期钩子,代码复杂度更高。
内容的提问来源于stack exchange,提问作者Altaïr
相关产品推荐
相关产品推荐

