![](/img/trans.png)
[英]Angular2 carrying data stored in a variable from app.component.ts(parent component) to other components
[英]Angular ngx-editor outsource config from app.component.ts in other components.ts file
带代码的LiveDemo参见此处https://stackblitz.com/edit/ngx-editor
在该项目中,您可以在app.component.ts文档中看到变量editorConfig包含编辑器的配置。
我想将此变量外包到文件中,因为我想根据使用目的加载不同的配置。
如果我创建一个componente,则页面不会加载。 如何创建仅包含变量的ngx-config-component.ts,之后如何集成此配置?
非常感谢您的帮助Christoph
我真的不明白为什么需要将其分成单独的文件,但是最好使用Angular的依赖注入机制。 我以stackblitz的分支为例: https ://stackblitz.com/edit/ngx-editor-ecaqtx
我在config.service.ts文件中创建了一个新服务:
import { Injectable } from '@angular/core';
@Injectable()
export class ConfigService {
editorConfig = {
editable: true,
spellcheck: false,
height: '10rem',
minHeight: '5rem',
placeholder: 'Type something. Test the Editor... ヽ(^。^)丿',
translate: 'no'
};
}
在app.module.ts中注册了它:
...
import { ConfigService } from './config.service';
@NgModule({
imports: [BrowserModule, FormsModule, HttpClientModule, NgxEditorModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
providers: [AppService, ConfigService]
})
export class AppModule { }
然后在app.component.ts中使用它:
...
import { ConfigService } from './config.service';
...
constructor(private _appService: AppService, private _configService: ConfigService) {
this.editorConfig = _configService.editorConfig;
}
...
您可以在此处了解有关Angular DI的更多信息: https : //angular.io/guide/dependency-injection
解决该问题的另一种方法是使用Angular路由器将配置作为数据参数传递,这样就可以使用同一组件在不同的路由上进行不同的配置。 您可以在此处了解更多信息: https : //angular.io/guide/router#router-state
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.