Last Updated on: (senast uppdaterad på:)
7 Steps are required to go from a URL holding a JSON result to the final presentation of results in an Angular component:
1>> have the JSON object, eg. localhost:8080/items/meenu_number/1
2>>Have a TypeScript interface that represents the object, eg. IItem
3>> Write the service class (eg. item.service.ts) with the observable on an http.get
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { Injectable } from '@angular/core'; import { IItem } from './item'; @Injectable({ providedIn: 'root' }) export class ItemService { private itemUrl = 'http://localhost:8080/items/menu_number/1'; constructor(private http: HttpClient) { } getItem(): Observable<IItem> { console.log("link is: " + this.itemUrl); return this.http.get<IItem>(this.itemUrl); } }
4>> Subscribe to the observable in the component and save it to a local variable. You can subscribe on the ngOnInit function of the component:
import { Component, OnInit } from '@angular/core'; import { ItemService } from './item.service'; import { IItem } from './item' @Component({ selector: 'app-show-item', templateUrl: './show-item.component.html', styleUrls: ['./show-item.component.css'] }) export class ShowItemComponent implements OnInit { constructor(private itemService: ItemService) { } item: IItem; ngOnInit(): void { console.log("ngOnInit accessed..."); this.itemService.getItem().subscribe({ next: gotItem => { this.item = gotItem[0]; console.log("- got item: " + JSON.stringify(gotItem)); console.log("- item menu number:" + gotItem[0].menu_number) }, error: err => console.log("error: " + err.error) }) } }
5>> Include the Http module in app.module.ts both as an import and in the imports section as HttpClientModule
//... import { HttpClientModule } from '@angular/common/http'; //... @NgModule({ declarations: [ AppComponent, ShowItemComponent, Logic10BaseIngredientsComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
6>> Enable Cross Origins on your server app, eg. the Node.js app:
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
7>> Include the object in the template file of your component
<div style="border:1px solid green"> <ng-container *ngIf="item"> <p>show-item component works!</p> {{ item.menu_number}} . {{ item.name }} <br> {{ item.description }} </ng-container> <app-logic10-base-ingredients></app-logic10-base-ingredients> </div>