Posts

Showing posts with the label Angular Services

Angular: 'Cannot Find A Differ Supporting Object '[object Object]' Of Type 'object'. NgFor Only Supports Binding To Iterables Such As Arrays'

Answer : As the error messages stated, ngFor only supports Iterables such as Array , so you cannot use it for Object . change private extractData(res: Response) { let body = <Afdelingen[]>res.json(); return body || {}; // here you are return an object } to private extractData(res: Response) { let body = <Afdelingen[]>res.json().afdelingen; // return array from json file return body || []; // also return empty array if there is no data } Remember to pipe Observables to async, like *ngFor item of items$ | async , where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair> , and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T. Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty You only nee...

Angular 4+ NgOnDestroy() In Service - Destroy Observable

Answer : OnDestroy lifecycle hook is available in providers. According to the docs: Lifecycle hook that is called when a directive, pipe or service is destroyed. Here's an example: @Injectable() class Service implements OnDestroy { ngOnDestroy() { console.log('Service destroy') } } @Component({ selector: 'foo', template: `foo`, providers: [Service] }) export class Foo implements OnDestroy { constructor(service: Service) {} ngOnDestroy() { console.log('foo destroy') } } @Component({ selector: 'my-app', template: `<foo *ngIf="isFoo"></foo>`, }) export class App { isFoo = true; constructor() { setTimeout(() => { this.isFoo = false; }, 1000) } } Notice that in the code above Service is an instance that belongs to Foo component, so it can be destroyed when Foo is destroyed. For providers that belong to root injector this will happen on application destroy, t...

Angular 5 Download Excel File With Post Request

Answer : I struggle with this one all day. Replace angular HttpClient and use XMLHttpRequest as follows: var oReq = new XMLHttpRequest(); oReq.open("POST", url, true); oReq.setRequestHeader("content-type", "application/json"); oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuffer = oReq.response; if (arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); console.log(byteArray, byteArray.length); this.downloadFile(byteArray, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.xlsx'); } }; oReq.send(body); Then modified the creation of the Blob in your downloadFile function: const url = window.URL.createObjectURL(new Blob([binaryData])); In your case the service will look something like this: DownloadData(model:requiredParams):Observable<any>{ return new Observable(obs => { var oReq = new XMLHttpReques...