我正在尝试实现通配符模块,我似乎没有得到它的工作:
现在我有以下代码可行:
typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import * as es from './i18n/es.json';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
hello = '-';
ngOnInit() {
this.hello = es.default.hello;
}
}
您可能会看到一个实例here,但我想实现WILDCARDS,如here(typescriptlang)和here(sitepen):
实现应该允许我做这样的事情:
typings.d.ts
declare module "*.json!i18n" {
const value: any;
export default value;
}
declare module "*.json!static" {
const value: any;
export default value;
}
declare module "*!text" {
const value: any;
export default value;
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import * as es from './i18n/es.json!i18n';
import * as someObject from './static/someObject.json!static';
import * as template1 from './templates/template1.html!text';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
hello = '-';
ngOnInit() {
this.hello = es.default.hello;
console.log(someObject.default);
console.log(template1.default);
}
}
问题是由于某些原因,通配符未被正确识别...在运行时抛出未找到“json”。
这个功能的一个例子是here,当它首次在Angular 2上实现时,
知道我做错了什么?
根据您分享的stackblitz code link,“静态”和“模板”目录不存在。只需创建目录并将数据放入其中。还要更新导入并从路径中删除!i18n
或!static
。
import * as es from './i18n/es.json';
import * as someObject from './static/someObject.json';
我只测试过static / someObejcts。模板也将以相同的方式工作。
app.component.ts
import { Component, OnInit } from '@angular/core';
import * as es from './i18n/es.json';
import * as someObject from './static/someObject.json';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
hello = '-';
ngOnInit() {
this.hello = es.default.hello;
console.log(es.default.hello);
console.log(someObject.default.hello);
}
}
typings.d.ts
declare module "*.json!i18n" {
const value: any;
export default value;
}
declare module "*.json!static" {
const value: any;
export default value;
}
Here是您的代码的一个工作示例