我開始學習Angular2,但..我想在我的成分,它創建一個服務和進口的,但我得到這個錯誤:Angular2:注射服務
error TS2339: Property 'commentService' does not exist on type 'CommentsComponent'.
comment.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class CommentService {
testfunction() {
return 'valoare';
}
}
comments.component.ts
import { Component, OnInit } from '@angular/core';
import { CommentService } from '../services/comment.service';
@Component({
template: 'dadada',
providers: [CommentService]
})
export class CommentsComponent implements OnInit {
construct(commentService: CommentService) {
}
ngOnInit() {
console.log(this.commentService.testfunction());
}
}
個
app.component.ts
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
selector: '[web-application]',
templateUrl: 'template/home',
directives: [ROUTER_DIRECTIVES]
})
export class AppComponent { }
app.routes.ts
import { provideRouter, RouterConfig } from '@angular/router';
import { CommentsComponent } from './components/comments.component';
import { HomeComponent } from './components/home.component';
const routes: RouterConfig = [
{ path: '', component: HomeComponent },
{ path: 'comments', component: CommentsComponent }
];
export const appRouterProviders = [
provideRouter(routes)
];
main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './components/app.component';
import { appRouterProviders } from './app.routes';
import { CommentService } from './services/comment.service'
bootstrap(AppComponent, [
appRouterProviders,
CommentService
])
.catch(err => console.error(err));
有人有一個想法,爲什麼我可以」注入服務?
我已經嘗試過了,但我得到了這個:參數屬性只允許在構造函數實現中。 –
我明白了。這聽起來很合理。雖然;構造函數應該被命名爲'constructor'而不是'construct'' –
Lol同樣的問題。我在「構造函數」一詞中出現語法錯誤:D – codepleb