Encountering an issue when attempting to call a method from the model in my component template.
error in ./NewsListComponent class NewsListComponent - inline template:3:12 caused by: self.context.$implicit.toggleState
After successfully fetching news from API and displaying them on the component template, I'm trying to implement a (click) event to toggle the state of the news items using the toggleState() method. Following the hero tour example.
Here's some code snippet:
news.model.ts
export class News {
constructor(
id: number,
title: string,
news: string,
path: string,
date: Date,
public state = 'inactive',
) {}
public toggleState()
{
this.state = (this.state === 'active' ? 'inactive' : 'active');
}
}
news.service.ts
import { Injectable } from '@angular/core';
import { Http,
Response,
Headers,
RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { News } from './news.model';
@Injectable()
export class NewsService {
private url = 'http://127.0.0.1:8000/app_dev.php/news';
constructor(private http:Http){}
getNews(): Observable<News[]> {
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({
headers: headers
});
return this.http
.get(this.url, options)
.map(this.extractData)
.catch(this.handleError);
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
private extractData(res: Response) {
let body = res.json()
return body || { };
}
}
news-list.component.ts
import {
Component,
OnInit,
Input,
trigger,
state,
style,
transition,
animate } from '@angular/core';
import { News } from './news.model';
import { NewsService } from './news.service';
@Component({
selector: 'news-list',
template: `
<div class="col-sm-8">
<h2>Noticias</h2>
<div class="media" *ngFor="let news_ of news"
[@newsState]="news_.state"
(click)="news_.toggleState()">
<div class="media-right media-middle">
<a href="#">
IMG
</a>
</div>
<div class="media-body media-middle">
<h4 class="media-heading">{{news_.title}}</h4>
<p>{{news_.news}}</p>
<hr>
</div>
</div>
</div>
`,
animations: [
trigger('newsState', [
state('inactive', style({
backgroundColor: '#eee',
transform: 'scale(1)'
})),
state('active', style({
backgroundColor: '#cfd8dc',
transform: 'scale(1.1)'
})),
transition('inactive => active', animate('100ms ease-in')),
transition('active => inactive', animate('100ms ease-out'))
])
],
})
export class NewsListComponent implements OnInit {
error: string;
@Input() news: News[];
mode = 'Observable';
constructor(private newsService: NewsService) {;
}
ngOnInit() {
this.newsService.getNews()
.subscribe(
(news: News[]) => this.news = news,
error => this.error = <any>error
);
}
}
news.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NewsService } from './news.service';
import { NewsListComponent } from './news-list.component';
@NgModule({
imports: [
CommonModule,
],
declarations: [
NewsListComponent
],
providers: [
NewsService
],
exports: [
NewsListComponent
],
})
export class NewsModule {}
Seeking help to resolve the following error.
Edit: Identified that News[]
is not properly filled with News objects. Error does not occur when explicitly creating a news object.
Solution provided by AJT_82, thank you!!
ngOnInit() {
this.newservice.getNews()
.subscribe(data => {
data.forEach(n => {
let newsObj: News = new News(n.id, n.title, n.news, n.path, n.date);
this.news.push(newsObj);
})
});
}