Angular 6 - 从孙子执行祖父母函数

问题描述 投票:0回答:1

我需要执行这些祖父母组件函数:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public loginPage = true;

  public login = function(){
    this.loginPage = false;
  }
  public logout = function(){
    this.loginPage = true;
  }
  
}

来自这个孙子组件:

import { Component, OnInit } from '@angular/core';

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

  constructor() { }

  ngOnInit() {
  }

  logout(){
    sessionStorage.removeItem('token');
    **//EXECUTE LOGOUT() GRANDPARENT FUNCTION HERE**
  }
}

我发现最接近我想要的示例是创建一个像这样的 DataService:

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

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

然后在组件中执行以下操作:

message: string;
this.data.currentMessage.subscribe(message => this.message = message)
//AND
this.data.changeMessage("Hello from Sibling")

但是我不想传递任何消息,我只想执行一个函数,所以我真的需要创建该 DataService 吗?我不能直接在祖父母组件中创建一个 Observable 或其他东西吗? 如果是这样,有人可以给我举个例子吗?

angular typescript rxjs
1个回答
3
投票

好的,我找到了解决方案,这就是我所做的。

我创建了一个 DataService,它接收子项的按钮单击并使其可观察,以便祖父母可以订阅该主题并检测更改并执行祖父母函数。

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

@Injectable()
export class DataService {

    private subject = new Subject();

    constructor() { }

    sendClickLogout() {
        this.subject.next();
    }

    clickLogout(): Observable<any>{
        return this.subject.asObservable();
    }

}

子组件:

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

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

  constructor(private dataService: DataService) { }

  ngOnInit() {
  }

  logout(){
    this.dataService.sendClickLogout();
  }

}

祖父母成分:

import { Component } from '@angular/core';
import { DataService } from '../app/services/data.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private dataService: DataService){
    this.dataService.clickLogout().subscribe(response => { this.logout() });
  }

  public loginPage = true;

  public logout = function(){
    sessionStorage.removeItem('token');
    this.loginPage = true;
  }
}

我希望这对像我一样的人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.