我使用angular4
创建了一个简单的服务以下是代码:
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyserviceService } from './myservice.service';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
//the service
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
constructor() { }
cars = ['fiat', 'form'];
myData() {
return 'Hello from service!';
}
}
//app.component.ts
import { Component, OnInit } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
constructor(private myservice: MyserviceService) {}
ngOnInit() {
console.log(this.myservice.cars);
this.something = this.myData();
}
}
我在这里遇到两个问题:
我在这里做错了什么?
答案 0 :(得分:2)
您正在访问app.component上的myData()
方法,它不是应用组件的成员。您必须使用myservice访问myData()
,例如
ngOnInit() {
console.log(this.myservice.cars);
this.something = this.myservice.myData();
}
其他一切对我来说都很好。