An issue arises when attempting to call a method from a component to a model as it is not

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

Answer №1

To resolve this issue, all you need to do is adjust your subscription slightly, like shown below:

ngOnInit() { 
    this.updatedService.getUpdates()
        .subscribe(response => {
            response.forEach(item => {
                let updatedObj: Updates = new Updates(item.id, item.title, item.update, item.link, item.timestamp);
                this.updatesList.push(updatedObj);
            })
        });
}

By following this approach, each update will be an instance of Updates with relevant methods such as the toggleState function.

I trust that this solution will work for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintain a continuous live server for your Angular 2/4 application

Is there a way to run an Angular application permanently? When I run the npm start command on a local server, it provides a URL with a port such as localhost:4200. However, when I close the terminal, the project stops running. The same issue occurs when ...

"Angular2: The Mysterious Disappearance of the Router

I'm facing an issue with defining a redirect from my login to the dashboard after successfully verifying a user. When I try to implement "this.router.navigate(['/dashboard'])" in my login component, I encounter the following error: "excepti ...

Guide on retrieving specific values within an array and mapping them to separate arrays using the HttpClient service in Angular 7+

I'm having a tough time grasping the concept of handling data once it's returned from an Http Request in Angular 7+ The Service responsible for fetching each location is shown below: import { Injectable } from '@angular/core'; import ...

The ReactJS Material Table Tree mode experiences delays when new row data is introduced

My Reactjs app utilizes the material-table widget within a component: render() { return ( <div> <Row> <MaterialTable title="Mon équipement" style={{ width: "100%", margin: "0%" }} ...

Error: The DatePipe in Angular is throwing an InvalidPipeArgument when trying to convert the object "[object Object]" into a date using data from PHP

I have an app built using Angular 9 and an API built with PHP. The PHP controller returns a list of objects with a property called finishDate. In PHP, finishDate is assigned to a DateTime object: $timeSheetsOrderDTO1 = new TimeSheetsOrderDTO; $timeSheetsOr ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

Table-driven forms in Angular

I am facing a requirement where I need to submit a form containing five records in a table format. Here is how the table looks: https://i.sstatic.net/82ZFM.png This is the code snippet for the form: <form [formGroup]="FeedBack" (ngSubmit)=&q ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

Tips for implementing [disabled] directive with dual options in Ionic Angular

Check out my page.html code: <ion-content *ngIf="charged"> Order ID: {{order.id_acg}} Item Weight(g): Height(cm): Width(cm): Length(cm): ...

Is there a way to trigger the "ngOnInit()" function again after navigating to the same URL but with a different parameter?

Within my application, there exists a URL structure such as /organization/campaign/{campaign handle}. The objective is to guide the user to a default campaign handle whenever they access the URL with an invalid {campaign handle}. For instance, if a user ...

How can `${}` be utilized within Angular applications?

Within TypeScript component files in Angular projects, I often come across this particular syntax enclosed in backticks: <div ${selector} [inDemo]="false" [config]="demoConfig">Demo Content</div> I'm curious about the purpose of the ${} ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Tips for setting up ngnix as a proxy server for Angular and NodeJS applications

Currently, I am working on configuring ngnix to run alongside both NodeJS and Angular. As of now, I can successfully access (Server API) and (Angular). However, when attempting to log in with socket.io, I consistently encounter a 'Socket connection ...

Efficiently resolving Angular's ngFor issues with Float functionality

I am currently developing a rating system that allows for half-star ratings, such as 3.5 or 4.5. Below is the code I have written: <div class="rating"> <i class="icon-star voted" *ngFor="let j of Arr(item.nbEtoile); let i = index;"></i& ...

What could be causing the issue where I am receiving the error message that says: "Unable to access properties of undefined (reading 'index')"?

Here is the code snippet from my template: <mat-tab-group mat-align-tabs="start" (selectedTabChange)="ngOnInit($event)"> This is the ngOnInit function: ngOnInit(evt: any) { this.api.getApi().subscribe( ({tool, beuty}) => ...

Leverage predefined JavaScript functions within an Angular template

I have been attempting to execute an eval function within my angular template in the following manner: <div *ngFor="..."> <div *ngIf="eval('...')"></div> </div> You understand what I'm trying to ...

Utilizing the functionalities provided by node.js, I came across an issue and sought out a solution for the error message "TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a function"

I have created a project centered around {typescript, react, electron, gaea-editor}. During an event, I utilized fs.writeFile() but encountered an error. The specific error message was: TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a functi ...

Troubden array filtration in Angular is malfunctioning

I recently developed an angular "filter component" intended to filter an array and display its contents. The keyword used to filter the array, value, is obtained from another component through a service. While the HTML displays both the value and the entir ...

Ways to inform websocket client of authentication failure

Utilizing the (ws package) in Node.js to handle websockets, I leverage the "on upgrade" event to authenticate incoming clients based on a token provided as a URL parameter. Following the guide here, if the token is invalid/missing/expired, I utilize the fo ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...