angular在服务中调用组件的某个方法,并传参给组件,(反向调用),变量改变后,强制更新视图
需要被调用方法的组件文件
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { SettingsService } from '@delon/theme';
import { SetdataService } from './setdata.service'
import { NgZone } from '@angular/core';
@Component({
selector: 'layout-header',
templateUrl: './header.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HeaderComponent {
searchToggleStatus: boolean;
constructor(
public settings: SettingsService,
// 組件頁面需要添加的代碼1
private testservice: SetdataService,
private zone: NgZone,
private cdf: ChangeDetectorRef
// 組件頁面需要添加的代碼2
) {
// 組件頁面需要添加的代碼1
this.testservice.testComponent$.subscribe(res => {
console.log(res) //這是接收到的參數
this.zone.run(() => {
this.test(res)
this.cdf.markForCheck(); // 进行标注
this.cdf.detectChanges(); // 要多加一行这个 执行一次变化检测
})
})
// 組件頁面需要添加的代碼2
}
myData = '000'
toggleCollapsedSidebar() {
this.settings.setLayout('collapsed', !this.settings.layout.collapsed);
}
searchToggleChange() {
this.searchToggleStatus = !this.searchToggleStatus;
}
// 組件頁面需要添加的代碼1
test(a) {
this.myData = a //第二个组件通过服务调用这个方法,并且传参过来改变页面
}
// 組件頁面需要添加的代碼2
}
创建一个服务,添加如下代码
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SetdataService {
constructor(
) { }
messageSubject = new Subject();
private testComponentSource = new Subject<boolean>();
testComponent$ = this.testComponentSource.asObservable();
// 这个就是方法可以调用传参给第一个组件
dummy(a) {
this.testComponentSource.next(a);
}
}
我们在另一个组件里调用这个服务的方法,就会连锁调用上个组件的那个方法~~
import { SetdataService } from '../../../layout/default/header/setdata.service'
export class UploadImgComponent implements OnInit {
constructor(
private ser: SetdataService
) { }
setData() {
this.ser.dummy('haha')
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决