I have an issue that I can't resolve. I'm learning Angular and I'm trying to get notifications from a JSON object through an API. Yet I get the error every time: error image
I used a service to get the data, as well as an interface for each Notification.
Code overview.component.html
<div >
<div >
<div >
<div >
<i ></i> Notifications
</div>
<div >
<div >
<app-notification *ngFor="let notification1 of notifications" icontje="{{notification1.icon}}" boodschapje="{{notification1.message}}"></app-notification>
<a >Load more...</a>
</div>
</div>
</div>
</div>
</div>
Code overview.component.ts
import { Component, OnInit } from '@angular/core';
import { Notificatie } from '../services/notification';
import { NotificationServiceService } from '../services/notification-service.service';
@Component({
selector: 'app-overview',
templateUrl: './overview.component.html',
styleUrls: ['./overview.component.css']
})
export class OverviewComponent implements OnInit {
notifications: Notificatie[] = [];
constructor(private NotificationService: NotificationServiceService) { }
ngOnInit(): void {
this.NotificationService.getNotifications().subscribe({next: data => {this.notifications = data;},error: error => {
console.log("This is an error: " error);
}})
}
// this.NotificationService.getNotifications().subscribe((notifications => (this.notifications = notifications)))
}
Code notification-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Observable } from 'rxjs';
import { Notificatie } from './notification';
@Injectable({
providedIn: 'root'
})
export class NotificationServiceService {
constructor(private http:HttpClient) { }
url = "http://www.mocky.io/v2/5be453402f00002c00d9f48f";
getNotifications():Observable<Notificatie[]>{
return this.http.get<Notificatie[]>(this.url)
}
}
Interface Notificatie
export interface Notificatie {
id:number;
message:string;
icon:string;
}
CodePudding user response:
Add HttpClientModule
to AppModule
imports