Reputation: 33
I try to inject service in my component and I get this error:
news.component.ts
import { Component,OnInit } from '@angular/core';
import { NewsService } from './index';
declare var jQuery:any;
@Component({
moduleId: module.id,
selector: 'news-selector-comp',
templateUrl:'news.html'
})
export class NewsSelectorComponent implements OnInit {
isLoading = true;
isError = false;
News:any;
constructor(public newsService:NewsService) { }
}
news.module.ts
news.service.ts
import {Http, Headers} from '@angular/http';
import { Injectable } from '@angular/core';
import { News, NewsImp } from './news';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class NewsService {
_url = '<%= SYSTEM_URL%>/news';
token = window.localStorage.getItem('token');
user_id = window.localStorage.getItem('user_id');
constructor(private _http:Http) {
}
getNews() : Observable<NewsImp[]> {
return this._http.get('https://jsonplaceholder.typicode.com/posts').map(res => res.json());
}
postNews() : Observable<News[]> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var news = {
user_id: this.user_id,
token : this.token
};
return this._http.post(this._url, JSON.stringify(news), {headers:headers}).map( res => res.json().data);
}
}
Upvotes: 0
Views: 2437
Reputation: 41
I have seen this issue myself, but for perhaps a different reason. I notice you are using the "barrels" approach here:
import { NewsService } from './index';
Try importing the NewsService class directly from the file it has been exported from. This seems to be a common issue.
Upvotes: 1
Reputation: 55443
Everything look okay according to your code expect below part.
import { BrowserModule } from '@angular/platform-browser';
import {NewsService} from './index';
@NgModule({
imports: [BrowserModule],
//In you main module, you should use BrowswerModule as shown here.
// In feature module you should use CommonModule
declarations: [NewsSelectorComponent],
providers: [NewsService],
bootstrap: [NewsSelectorComponent]
})
I think this code should work.
Upvotes: 0