【问题标题】:Using variable in another Angular component without Input() method在没有 Input() 方法的情况下在另一个 Angular 组件中使用变量
【发布时间】:2022-07-28 23:27:19
【问题描述】:

我需要在另一个组件中使用“onlineBookingDisabledMessage”,但我不想使用 Input() 方法。如何让该组件知道“onlineBookingDisabledMessage”?

我想显示存储在该变量和另一个组件中的消息。

谢谢。

import { Store } from '@ngrx/store';
import { Component, OnInit, Input } from '@angular/core';
import * as fromRoot from './../../../ngrx';
import { BookingActions } from '../../actions/booking.actions';
import { ActivatedRoute } from '@angular/router';
import { AuthHelperService, StartupService } from '../../../core/services';
import { Location } from '@angular/common';


@Component({
  selector: 'pp-previus-visit-step-page',
  templateUrl: 'previus-visit-step-page.component.html',
  styleUrls: ['previus-visit-step-page.component.scss'],
})
export class PreviusVisitStepPageComponent implements OnInit {
  isExistingPatient;
  useOnlineBooking = true;
  loginEnabled = false;

  onlineBookingDisabledMessage;
  redirectLoginUrl;

  constructor(
    private store: Store<fromRoot.State>,
    private route: ActivatedRoute,
    private startupService: StartupService,
    private location: Location,
    private navigateService: NavigateWrapperService,
    public authHelperService: AuthHelperService
  ) {
    this.store.dispatch(new BookingActions.SetQueryParamLocationAction(this.route.snapshot.params['locationGuid']));

    this.useOnlineBooking = startupService.startupData.useOnlineBooking;
    this.loginEnabled = this.startupService.startupData.usePatientPortal;

    this.onlineBookingDisabledMessage = startupService.startupData.onlineBookingDisabledMessage;

    this.navigateService.pushRoute('booking/previous-visit', false);
  }

  ngOnInit() {
    this.redirectLoginUrl = 'appointments';
  }

}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以使用BehaviourSubject 的服务

    export class DataService {
      private dataSource: BehaviorSubject<string> = new BehaviorSubject<string>('Initial Value');
      data: Observable<string> = this.dataSource.asObservable();
     
      constructor() { }
     
      sendData(data: string) {
        this.dataSource.next(data);
      }
    }
    

    接收器组件:

    export class ReceiverComponent implements OnInit {
     
      constructor(private dataService: DataService) { }
     
      ngOnInit(): void {
        this.getData();
      }
     
      getData() {
        this.dataService.data.subscribe(response => {
          console.log(response);  // you will receive the data from sender component here.
        });
      }
    }
    

    或者您可以使用 EventEmitter 在组件之间共享数据

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 2023-03-13
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      相关资源
      最近更新 更多