角度2/5组件交互

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

我有一个警卫服务,应该更改我的app.componant的成员。为此,我在app.componant创建了一个setter。这个setter应该由guard-service执行。我想通过输入和输出来实现。

import {AppComponent} from './app.component';
import {Injectable, Input} from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuardService implements CanActivate {
    @Input() appc: AppComponent;                         
    canActivate(): boolean {
        if(!online) {                                    //if status isn't online
            this.router.navigate(['loginEmail']);        //go to loginpage
            this.appc.changeHeaderEnable(false);         //change value
            return false;
        }
        this.appc.changeHeaderEnable(true);
        return true;
    }
}

如果这样可行,我需要在我的AppComponant中使用@Output()作为装饰器的方法changeHeaderEnable():

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

@Injectable()
export class AppComponent {
  headerEnabled = true;
  @Output()
  changeHeaderEnable(b: boolean) {
      this.headerEnabled = b;
  }
}

我将两个组件都缩减为重要内容。现在我希望每次我链接到一个不同的路由,其中​​AuthGuardService作为一个后卫,canActivate()应该执行。但每次我链接到另一台路由器,我得到以下错误:

错误:未捕获(在承诺中):TypeError:无法读取未定义的属性'changeHeaderEnable'

为什么在我的警卫服务中未定义changeHeaderEnable?我错了什么?

angular
1个回答
1
投票

装饰器@Input和@Output用于父组件和子组件之间的属性绑定。您不能像在服务中那样在服务中使用它们。它们依赖于变化检测,这仅适用于组件和指令。

老实说,提供的代码有很多问题。我看到你还用@Injectable而不是@Component装饰你的app.component,这是另一个大问题。默认情况下,所有组件(和指令)都是可注入的。

如果你还没有,我建议你完成Angular教程:Angular Tutorial

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