我正在尝试在组件中实例化服务。我收到了这个错误
未捕获错误:无法解析所有参数 AuthenticationService :(?,[object Object],?)。
这是我的服务
@Injectable()
export class AuthenticationService {
protected basePath = 'http://localhost:8080/rest';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional() @Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
}
public login(authenticationkey?: string, body?: AuthenticationRequestHolder, extraHttpRequestParams?: any): Observable<AuthenticationBundle> {
return this.loginWithHttpInfo(authenticationkey, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return FlexiCoreDecycl`enter code here`e.retrocycle(response.json()) || {};
}
});
}
// More Code
这是使用服务的组件
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private _authenticationService: AuthenticationService) {
}
ngOnInit() {
this._authenticationService
.login('', {mail: 'admin@example.com', password: 'admin'})
.subscribe(response => {
console.log(response);
},
error => {
console.log(error);
});
}
}
这里是角度模块
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule
],
providers: [AuthenticationService],
bootstrap: [AppComponent]
})
export class AppModule { }
任何人都可以帮助我如何正确连接它们吗?我是角度和打字稿的新手,所以,我会欣赏一点点解释和指示。
答案 0 :(得分:4)
可能有另一种方式,但这是我如何解决它。使用FactoryBuider。 这就是我的app.module喜欢的内容
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {LoginComponent} from './login/login.component';
import {AuthenticationService, BASE_PATH, Configuration} from '@hanoch/fc_client';
import {Http, HttpModule} from '@angular/http';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
HttpModule,
FormsModule
],
providers: [
Configuration,
{
provide: AuthenticationService,
useFactory: AuthenticationServiceFactory,
deps: [Http]
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
export function AuthenticationServiceFactory(http: Http) {
return new AuthenticationService(http, 'http://localhost:8080/rest', Configuration);
}
答案 1 :(得分:0)
您需要在HttpModule
中的导入中添加AppModule
,因为类Http
是在HttpModule中定义的角度服务。
imports: [
BrowserModule,
HttpModule
],
如果您要注入basePath
和configuration
,您应该添加提供商:
providers: [
{
provide: BASE_PATH,
useValue: 'https://google.com' // replace with yours
},
{
provide: Configuration,
useValue: new Configuration() // replace with correct instance
}
AuthenticationService
]
您可以在角度教程中阅读很多关于依赖注入的内容:Angular: Dependency Injection