无参数构造函数可以工作,但是当我尝试注入任何内容时,页面返回运行时错误:
无法解析AppComponent的所有参数:(?)
知道问题可能是什么?这是代码:
app.module.ts :
www.example.com
app.component.ts :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { environment } from '../environments/environment';
import { MyService } from './my.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFireDatabaseModule,
AngularFireModule.initializeApp(environment.firebase)
],
//providers:[],
providers: [MyService],
bootstrap: [AppComponent]
})
export class AppModule { }
my.service.ts :
import { Component, Inject, Injectable, HostListener } from '@angular/core';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { VendingMachineService } from './vending-machine.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
/*
constructor()
{
}
*/
constructor(ms)
{
var x = vms;
}
}
答案 0 :(得分:1)
重写
app.component.ts:
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { VendingMachineService } from './vending-machine.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
//please check vendingMachineService, this is not the name of the service you provided in code
constructor(private vendingMachineService: VendingMachineService){}
/*
constructor(ms) what is ms????? remove
{
var x = vms;
}
*/
}
为什么要导入已在应用模块中导入的模块?如果你想这样做,我不这么认为,你需要申报另一个模块
您可能想考虑将服务重命名为my-service.service.ts
,看起来更好
答案 1 :(得分:0)
如果要将MyService注入组件,那么构造函数应如下所示:
import { Component, Inject, Injectable, HostListener } from '@angular/core';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { VendingMachineService } from './vending-machine.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// CLASS as type is required for Angular to match to your service
// otherwise angular doesn't know what to inject
// Also I have added the access modifier private
// which creates an field so you can access via this.myservice
constructor(private myService: MyService){
}
// Example usage in a method:
someMethod(){
this.service.doSth();
}
}