从组件调用模型方法时,错误不是函数

时间:2017-01-11 21:58:21

标签: angular typescript

当我尝试从组件模板调用模型方法时,我收到此错误。

error in ./NewsListComponent class NewsListComponent - inline template:3:12 caused by: self.context.$implicit.toggleState

我从API获得新闻,我可以在组件模板上看到新闻。然后我尝试添加(点击)事件并从新闻中调用toggleState()方法。我只是在英雄之旅后做点什么。

这里我展示了一些代码

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 || { };
    }   
}

新闻-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 {}

我做错了什么? 提前谢谢。

编辑:似乎News[]并没有真正填充新闻对象,如果我明确地创建了一个新闻对象,我就不会收到错误。

AJT_82解决了问题,谢谢!!

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);
            })
        });
}

1 个答案:

答案 0 :(得分:2)

这应该清除,只需更改您的订阅,如下:

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);
            })
        });
}

这样每条新闻都会成为News的一个实例,并且会有适当的方法,例如你的toggleState方法。

希望这有帮助!