我想使用可注入服务,该服务可在自定义装饰器中读取,以了解其他组件的更改。
问题是我没有用于注入此服务的构造函数,如果我创建此服务的实例,则读取该组件的组件显然不会读取更改。
我如何注射?
在将原始构造函数更改为具有我要注入的服务以及原始构造函数的其他参数的过程中,我取得了一些进展。这样做,我就有了服务,并且可以访问其中的方法,但是在尝试在组件中调用它时抛出错误:
代码:
const navbar= <T>(originalConstructor: new(...args: any[]) => T) => {
function newConstructor(navbarService: NavbarService, ...args) {
new originalConstructor(navbarService, args);
}
//Here I can take the service for operate with it, I think
newConstructor.prototype = originalConstructor.prototype;
return newConstructor;
}
@Component({
selector: 'app-wizard',
templateUrl: './wizard.component.html',
styleUrls: ['./wizard.component.scss']
})
@navbar //Here it throws me the error belo
export class WizardComponent {
constructor(
private formBuilder : FormBuilder,
private snackBar : MatSnackBar,
private router : Router
) {}
}
错误:
[ts]
Unable to resolve signature of class decorator when called as an expression.
Type '(navbarService: NavbarService, ...args: any[]) => void' is not assignable to type 'typeof WizardComponent'.
Type '(navbarService: NavbarService, ...args: any[]) => void' provides no match for the signature 'new (formBuilder: FormBuilder, snackBar: MatSnackBar, router: Router): WizardComponent'.
忽略这一点,我正在寻找另一个可以解决我主要问题的解决方案:在装饰器中注入服务。
这是装饰器的代码,调用它的组件,服务以及等待服务更改的组件:
装饰员和呼叫者:
const navbar= <T>(originalConstructor: new(...args: any[]) => T) => {
function newConstructor(navbarService: NavbarService, ...args) {
new originalConstructor(navbarService, args);
}
//Here I can take the service for operate with it, I think
newConstructor.prototype = originalConstructor.prototype;
return newConstructor;
}
@Component({
selector: 'app-wizard',
templateUrl: './wizard.component.html',
styleUrls: ['./wizard.component.scss']
})
@navbar //Here it throws me the error below
export class WizardComponent {
constructor(
private formBuilder : FormBuilder,
private snackBar : MatSnackBar,
private router : Router
) {}
}
服务:
@Injectable({ providedIn: 'root' })
export class NavbarService {
service = new BehaviorSubject(null);
constructor() { }
openNavbar() {
this.service.next('open');
}
closeNavbar() {
this.service.next('close');
}
}
等待服务更改的组件:
@ViewChild('sidenav') sidenav: MatSidenav;
constructor(
private navbarService : NavbarService
) {}
ngOnInit() {
this.navbarService.service.subscribe(options => {
if(options == 'open') this.sidenav.open();
else if(options == 'close') this.sidenav.close();
});
}
谢谢。
编辑:我找到了一个部分解决方案,但它专注于函数装饰器,对于组件/类装饰器,我也需要类似的解决方案。
Here是我需要修改的解决方案!