1

根据文档和 git-hub 问题评论,我正在尝试实现一个自定义注入器,以将数据传递给我使用@angular/cdk和动态加载的组件cdkPortalOutlet。我可以看到 PortalInjector 被成功创建,InjectorToken但是在尝试获取/使用data动态加载的组件时,我总是得到一个null.

数据/injector.ts

import {InjectionToken,Injector} from '@angular/core';
import {PortalInjector} from '@angular/cdk/portal';
export const CONTAINER_DATA = new InjectionToken<{}>('CONTAINER_DATA');
export class DataInjector{
public createInjector(dataToPass,_injector): PortalInjector {
const injectorTokens = new WeakMap();
injectorTokens.set(CONTAINER_DATA, dataToPass);
return new PortalInjector(_injector, injectorTokens);
}
} 

组件/base.component.ts

   var  di:DataInjector= new DataInjector();
   var   pi:PortalInjector=di.createInjector("AutoMode",this._injector);
   console.log("portalinjector passed is:");
   console.log(pi);
   cportal:Portal<any>=new ComponentPortal(ToolbarComponent,null,pi));

工具栏组件

import { Component, Inject,OnInit } from '@angular/core';
import {CONTAINER_DATA} from '../../data/injector';
@Component({
selector: 'app-toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.css']
})
export class ToolbarComponent implements OnInit {
@Inject(CONTAINER_DATA) public componentData: any
constructor() {
console.log("ToolbarComponent^dataobtained constructo is:");
console.log(this.componentData);// prints null
  }

ngOnInit() {
console.log("ToolbarComponent^dataobtained is:");
console.log(this.componentData); //prints null
}

}

标记为 //prints null 的行,总是 prints null。然而

 console.log("portalinjector passed is:");
 console.log(pi);

印刷 :

   PortalInjector {_parentInjector: Injector_, _customTokens: 
   WeakMap}_customTokens: WeakMap {InjectionToken => 
   "AutoMode"}_parentInjector: Injector_ {view: {…}, elDef: {…}}__proto__: 
   Object

如果我遗漏了什么,有人可以告诉我吗?

4

0 回答 0