I am very new to Angular and typescript and have been reading some posts about returning typed data. Some articles state you have to map your objects after returning them from the service, others just type the result in the call. What the easiest way in Angular 6 to get strongly typed data? The below doesn't work do I really need to map each property manually?
My model:
export interface MenuItem {
menuItemsId:number;
groupCode: number;
groupDescription: string;
subGroupCode:number;
subGroupDescription:string;
itemCode:number;
itemDescription:string;
grade:string;
remark:string;
}
My service:
getValues():Observable<MenuItem[]>{
return this.httpClient.get<MenuItem[]>("https://hafnia-asset-control-dev.azurewebsites.net/api/menuitems/cosmetic");
}
Call:
var t = this.apiService.getValues().subscribe((data) => {
this.menuItems = data;
console.log(this.menuItems);
});
JSON result:
[{"menuItemsId":1,"groupCode":1000,"groupDescription":"xxx","subGroupCode":1000,"subGroupDescription":"SHELL","itemCode":1001,"itemDescription":"ccc","grade":"Int","remark":"String"},{"menuItemsId":2,"groupCode":1000,"groupDescription":"COSMETIC","subGroupCode":1000,"subGroupDescription":"xxx","itemCode":1002,"itemDescription":"xxx","grade":"Int","remark":"String"}
app.module:
providers: [AdalService, AdalGuard,{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }],
Interceptor:
import { Injectable } from '@angular/core';
import { HttpEvent,HttpHandler,HttpRequest,HttpInterceptor } from '@angular/common/http';
import { AdalService } from 'adal-angular4';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private adalService: AdalService) { }
intercept(req: HttpRequest<any>, next:HttpHandler): Observable<HttpEvent<any>>{
const authHeader = this.adalService.userInfo.token;
const authReq = req.clone({headers: req.headers.set('Authorization', `Bearer ${authHeader}`)});
return next.handle(authReq);
}
}
get<MenuItem[]>notget<Array<MenuItem>>, and it will only work if that URL returns an array which matches MenuItem, else you will appear to have no datayou should use get<MenuItem[]> not get<Array<MenuItem>><= same thing, see Array<Type> VS Type[] in Typescript