为了在我的项目中获得更好的文件管理,我想提取提供程序并将外部文件作为常量放入。这是我与提供商的第一次体验。 我想得到这个文件结构:
angular.module('MyApplication', []).config(["$httpProvider", function ($httpProvider) {
var token = document.querySelector('meta[name=csrf-token]').content;
$httpProvider.defaults.headers.common['X-CSRF-Token'] = token;
}])
|- src/
|- common/
|- providers/
|- parent.provider.ts
... others providers
|- components/
|- foo.component.ts
... others components
// Helper method to provide the current component instance in the name of a `parentType`.
// The `parentType` defaults to `Parent` when omitting the second parameter.
export const provideParent =
(component: any, parentType ? : any) => {
return { provide: parentType || Parent, useExisting: forwardRef(() => component) };
};
目前我在编译期间遇到此错误:
错误TS4023:导出的变量' provideParent'已经或正在使用名称' Type'从外部模块" path /到/ application / node_modules / @ angular / core / src / type"但无法命名。
提供者应该在模块内吗? ......有人有想法吗?
答案 0 :(得分:0)
必须在模块级别指定提供者。所以如果你有结构:
|- src/
|- common/
|- providers/
|- parent.provider.ts
... others providers
|- components/
|- foo.component.ts
... others components
您必须将组件分组到模块中:
|- src/
|- common/
|- providers/
|- parent.provider.ts
... others providers
|- module1/
|- foo.component.ts
|- bar.component.ts
然后,您可以在module1定义中指定foo和bar的提供程序。
答案 1 :(得分:0)
我找到了解决方案。我的示例基于此Angular example和此code(请参阅parent-finder.component.ts)。 要外部化帮助方法以为每个组件生成自定义提供程序,我有以下代码:
import { Component, forwardRef } from '@angular/core';
...
// Marker class, used as an interface
export abstract class Parent { name: string; }
...
// Helper method to provide the current component instance in the name of a `parentType`.
// The `parentType` defaults to `Parent` when omitting the second parameter.
const provideParent =
(component: any, parentType?: any) => {
return { provide: parentType || Parent, useExisting: forwardRef(() => component) };
};
...
@Component({
selector: 'foo',
...
providers: [ provideParent(FooComponent) ]
})
export class FooComponent implements Parent
{
name= 'Foo';
}
我必须这样做:
|- src/
|- common/
|- helpers/
|- provider.helper.ts
...
|- components/
|- foo.component.ts
...
//Old code
/*const provideParent = (component: any, parentType ? : any) => {
return { provide: parentType || Parent, useExisting: forwardRef(() => component) };
};*/
// Right code
export function provideParent(component: any, parentType ? : any): Provider {
let provider: Provider = { provide: parentType || Parent, useExisting: forwardRef(() => component) };
return provider;
}
import {provideParent} from '../common/helpers/provider.helper';
...
@Component({
selector: 'foo',
...
providers: [ provideParent(FooComponent) ]
})
export class FooComponent implements Parent
{
name= 'Foo';
}