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')
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM