我正在使用帶有角度1.6.x和Typescript的Webpack,並且我退出了使用角度DI來支持ES6導入。當我需要一個像$http
,$resource
和這樣一些NG功能,我把他們注入直接使用angular.injector
功能通過一個裝飾,如:AngularJS - 使用ES6導入代替角度DI系統
// inject.ts
import * as angular from 'angular';
export function inject (...params: string[]) {
function doCall (param: string, klass: Function) {
const injector = angular.injector([ 'ng' ]);
const service = injector.get(param);
try {
klass.prototype[ param ] = service;
} catch (e) {
window.console.warn(e);
}
}
// tslint:disable-next-line:ban-types
return function (klass: Function) {
params.forEach((param) => {
doCall(param, klass);
});
};
}
// posts.service.ts
import { inject } from './inject';
import { IPost, Post } from './post';
@inject('$http')
export class PostsService {
public $http: angular.IHttpService;
get(): Promise<IPost[]> {
const posts: IPost[] = [];
const promise = new Promise<IPost[]>((resolve, reject) => {
this.$http.get<IPost[]>('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
response.data.forEach(item => {
posts.push(new Post(item));
});
resolve(posts);
});
});
return promise;
}
}
// post.ts
export interface IPost {
userId: number;
id: number;
title: string;
body: string;
}
export class Post implements IPost {
userId: number;
id: number;
title: string;
body: string;
constructor (item: IPost) {
this.userId = item.userId;
this.id = item.id;
this.title = item.title;
this.body = item.body;
}
}
// controller.ts
import { IPost } from './post';
import { PostsService } from './posts.service';
export class Controller {
public postService: PostsService;
public posts: IPost[];
constructor (private $scope: angular.IScope) {
this.postService = new PostsService();
}
$onInit() {
this.postService.get()
.then((posts) => {
this.posts = posts;
this.$scope.$digest();
});
}
}
// index.ts
import * as angular from 'angular';
import { Controller } from './app/controller';
import './index.scss';
export const app: string = 'app';
angular
.module(app, [])
.controller('controller', Controller);
angular.bootstrap(document.body, [app]);
我不知道這是否符合最佳實踐與否,但目前它的工作狀況非常好。
我想聽聽你對這個問題的想法:使用這種方法是否存在任何問題(表現,不良習慣等)?
角度模塊/ DI和ES6模塊相互補充。它們不可互換。 *直接使用angular.injector * - 這是非常錯誤的,你很少需要使用'angular.injector',因爲它沒有達到你期望的效果。 – estus
我覺得這是一個很好的問題,但在這裏寫的地方不合適。你有代碼是完全有效的,這是第一個紅旗,以及聲明「我想聽聽你對這個主題的想法」,這幾乎直接在[dont-ask]中引用(https://stackoverflow.com /幫助/不-問)。我認爲這個問題是有價值的,但是你可能想要考慮將其重新說成更多關於這種技術的問題和原因,而不是討論問題。 – Claies