获取Angular中不相关组件的属性

问题描述 投票:-2回答:2

如果不相关,我如何获得另一个组件的属性。我知道可共享服务,还有其他方法吗?

angular
2个回答
1
投票

您可以在RxJ中使用Observables

//message.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class MessageService {

  private messageCommand = new Subject<string>();
  messageCommand$ = this.messageCommand.asObservable();

  invokeMessage(msg: string) {
    this.messageCommand.next(msg);
  }
}

//component-one.ts

import { Component, OnInit } from '@angular/core';
import { MessageService } from '../services/message.service';

@Component({
  selector: 'app-component-one',
  templateUrl: './component-one.component.html',
  styleUrls: ['./component-one.component.css']
})
export class ComponentOneComponent implements OnInit {

  constructor(private messageService: MessageService) { }

  ngOnInit() {
  }

  yourActionMethod() {
    this.messageService.invokeMessage('This is from component one');
  }
}

//component-two.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { MessageService } from '../services/message.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-component-two',
  templateUrl: './component-two.component.html',
  styleUrls: ['./component-two.component.css']
})
export class ComponentTwoComponent implements OnInit, OnDestroy {

  messageSubscription: Subscription;
  message: string;

  constructor(private messageService: MessageService) { }

  ngOnInit() {
    this.subscribeToMessageEvents();
  }

  ngOnDestroy(): void {
    this.messageSubscription.unsubscribe();
  }

  subscribeToMessageEvents() {
    this.messageSubscription = this.messageService.messageCommand$.subscribe(
      (msg: string) => {
        this.message = msg;
      }
    );
  }

}

这里我使用了一个包含一个可观察类型字符串的服务类。

然后从component-one中,使用我们的消息服务中的invokeMessage方法发布消息。

需要接收消息的组件,在我们的例子中,组件二应该订阅消息服务中的messsageCommand $。

始终确保在销毁组件时取消订阅订阅。


1
投票

嗨@Aspram你应该创建一个输出或共享服务来执行此操作。

我给你看

与@output()

header.component.ts

export class Header implements OnInit {

  @Output() onheaderInit: EventEmitter<Header> = new EventEmitter<Header>();

  constructor() { }

  ngOnInit() {
    this.onheaderInit.emit(this);
  }
}

然后你可以消耗它

<header (onheaderInit)="getTheClass($event)">

第二种方法使用Subject

sharedService.ts

import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {

  public onheaderInit: Subject<any> = new Subject();

  constructor() { }

}

header.component.ts

export class Header implements OnInit {

  constructor(private _sharedService: SharedService) { }

  ngOnInit() {
    this._sharedService.onheaderInit.next(this);
  }
}

然后你可以消耗它

this._sharedService.onheaderInit.subscribe( res => {
  console.log(res)
});
© www.soinside.com 2019 - 2024. All rights reserved.