如何在 Angular 5 组件中使用 AngularJS 服务?
我有 AngularJS 应用程序,我正在尝试制作混合应用程序,但无法使用 AngularJS 服务洞察 Angular 组件:出现错误
ERROR 错误:试图在设置之前获取 AngularJS 注入器。
我的 main.ts 是
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
应用程序模块:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, InjectionToken } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UpgradeModule, downgradeComponent } from '@angular/upgrade/static';
import { AppComponent } from './app.component';
import { SignInComponent } from "./modules/login/components/sign-in/sign-in.component";
import { authServiceProvider } from './shared/angularJS-upgraded-providers';
@NgModule({
declarations: [
AppComponent,
SignInComponent
],
imports: [
BrowserModule,
UpgradeModule,
FormsModule
],
entryComponents: [
SignInComponent
],
providers: [authServiceProvider],
bootstrap: [SignInComponent]
})
export class AppModule {
ngDoBootstrap() {}
}
angularJS-upgraded-providers.ts :
import { InjectionToken } from "@angular/core";
export const AuthService = new InjectionToken<any>('authService');
export function authServiceFactory(i: any) {
return i.get('authService');
}
export const authServiceProvider = {
provide: AuthService,
useFactory: authServiceFactory,
deps: ['$injector']
};
和 login.component.ts :
import { Component, Inject } from '@angular/core';
import {AuthService} from "../../../../shared/angularJS-upgraded-providers";
@Component({
selector: 'sign-in',
template: require('./sign-in.component.html')
})
export class SignInComponent {
constructor(
@Inject(AuthService) private authService: any) {
}
}
当我删除 SignInComponent 构造函数部分代码编译良好但 @Inject(AuthService) private authService: any) { } 部分我收到一个错误:
尝试在设置之前获取 AngularJS 注入器。
请给我一些建议,我该如何实现 angularJS 服务洞察 Angular 组件。谢谢
PS我的package.json:
{
"name": "test",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "webpack-dev-server --port=4200 --open chrome"
},
"dependencies": {
"@angular/common": "^5.2.11",
"@angular/compiler": "^5.2.11",
"@angular/core": "^5.2.11",
"@angular/forms": "^5.2.11",
"@angular/http": "^5.2.11",
"@angular/platform-browser": "^5.2.11",
"@angular/platform-browser-dynamic": "^5.2.11",
"@angular/router": "^5.2.11",
"@angular/upgrade": "^5.2.11",
"core-js": "^2.5.7",
"reflect-metadata": "^0.1.12",
"rxjs": "^5.5.11",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@types/jquery": "^3.3.6",
"@types/node": "^8.10.23",
"awesome-typescript-loader": "^5.2.0",
"css-loader": "^1.0.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"raw-loader": "^0.5.1",
"style-loader": "^0.22.1",
"ts-loader": "3.2.0",
"typescript": "^2.9.2",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
和 AngularJS 版本:1.6.8