将注入器服务插入类装饰器

时间:2019-03-04 07:58:25

标签: angular typescript

我正在尝试在Angular项目中使用类装饰器 我有一个界面

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

export interface SessionAwareComp {
    injector: Injector;
    isLoggedIn: boolean;
    ngOnInit?: Function;
}

我在装饰器和组件中使用的

import { Component, OnInit, Injector } from '@angular/core';
import { SessionAware } from 'src/app/decorators/session-aware';
import { SessionAwareComp } from 'src/app/contracts';

@Component({
  selector: 'app-desktop-header',
  templateUrl: './desktop-header.component.html',
  styleUrls: ['./desktop-header.component.scss']
})
@SessionAware()
export default class DesktopHeaderComponent implements OnInit, SessionAwareComp {
  isLoggedIn: boolean;
  constructor(public injector: Injector) {
  }

  ngOnInit() {
  }
}

装饰器

import { SessionAwareComp } from '../contracts';
import { SessionService } from '../services/session.service';

export function SessionAware() {
   return (classProto: SessionAwareComp) => {
       const ngOnInit = classProto.ngOnInit;

       classProto.ngOnInit = function(this: SessionAwareComp) {
            // const session = this.injector.get(SesssionService)
            // throws error `cannot call get on undefined`
            console.log(this); // Always undefined
            ngOnInit && ngOnInit.apply(this);
       };
   }
}

我遇到了两个问题;

  1. this中的classProto.ngOnInit始终未定义

  2. Typescript引发编译错误:

Argument of type 'typeof DesktopHeaderComponent' is not assignable to parameter of type 'SessionAwareComp'.
  Type 'typeof DesktopHeaderComponent' is missing the following properties from type 'SessionAwareComp': injector, isLoggedIn

尽管设置了isLoggedIninjector属性。

不确定我在做什么错,这是我第一次尝试使用Angular中的装饰器

0 个答案:

没有答案