我需要执行以下祖父母组件功能:
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吗? 如果是这样,有人可以给我举个例子吗?
答案 0 :(得分:0)
好的,我找到了解决方案,这就是我所做的。
我创建了一个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;
}
}
我希望这对像我这样的人有帮助。