angular在服务中调用组件的某个方法,并传参给组件,(反向调用),变量改变后,强制更新视图
2024-08-30 13:25:23
需要被调用方法的组件文件
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')
}
最新文章
- *HDU 1115 计算几何
- C#的参数修饰符out,params,ref
- LinuxShell脚本攻略--第二章 命令之乐
- 蓝桥杯---汉字取首字母(位运算 &; 水题)
- MD5加密(C#)
- MQTT开发小记(一)
- Qt, QT/E, Qtopia 的区别
- 程序员带你十天快速入门Python,玩转电脑软件开发(二)
- Linux中解决SSH连接慢问题
- java 下载文件 内容为空。
- JSP(一)
- cocos2d-js-v3.0-rc0 下 pomelo-cocos2d-jsb native web 配置
- Spring之SpringMVC的RequestToViewNameTranslator(源码)分析
- ettercap的中间人欺骗
- 用户态Linux内核
- Linux下php安装redis扩展(redis已经安装)
- k8s部署rocketmq 双主
- TEA加密/解密算法
- python记录_day02 while循环 格式化 基本运算符
- php版本CKEditor 4和CKFinder安装及配置