zoukankan      html  css  js  c++  java
  • 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')
      }

  • 相关阅读:
    如何保持页脚始终在页面底部
    CSS自适应宽度圆角按钮
    ACM1004
    java输出格式
    北大ACM1001题Exponentiation(求高精度幂)
    深入理解sizeof
    java之类BigDecimal
    ACM1003
    ACM1005
    C的输出格式printf
  • 原文地址:https://www.cnblogs.com/sugartang/p/12605162.html
Copyright © 2011-2022 走看看