Exploring the Power of PrimeNG and Observables in Angular 4 with RxJS

After configuring my Angular 4 project with a service like this:

const usersURL = 'http://my.super.url.php';


@Injectable()
export class UserService {



  users: Observable<User[]>

    constructor (public http:Http)

 let tick$ = Observable.timer(100, 60000);


          this.users = tick$.flatMap(() => http.get(usersURL)).map(res => [res.json()]).publishBehavior(<User[]>[]).refCount();

I came across the PrimeNg library which predominantly uses promises by default as shown here:

 @Injectable()
export class CarService {

    constructor(private http: Http) {}

    getCarsSmall() {
        return this.http.get('/showcase/resources/data/cars-small.json')
                    .toPromise()
                    .then(res => <Car[]> res.json().data)
                    .then(data => { return data; });
    }
}

I am wondering about the best approach to quickly integrate this library. Should I modify my service to work with promises or should I adjust the code from the PrimeNG documentation? This is my first time working with PrimeNg so any guidance on how to handle this considering that a lot of my existing code relies on Observables would be appreciated. Thank you in advance. You can find more information in the PrimeNg docs here.

Here is an example of my JSON data:

 {"status":"OK","data":{"apps":{"weather_icon":"storm","running":    {"current":6,"total":12,"sensitive":{"current":1,"total":6},"non_sensitive":{"current":5,"total":6}},"non_running":{"current":6,"sensitive":{"current":5,"unseen":2,"acknowledged":0,"assigned":3},"non_sensitive":{"current":1,"unseen":0,"acknowledged":0,"assigned":1}},"availability": {"current":8,"trend":-6.6},"details":[{"id":1,"label":"Gestion administrative des patients (ORBISAdm)","state":"Critique","state_id":2,"weather_icon":"storm","since":"2h37mn","availability":{"current":68,"trend":"-"},"acknowledged":1,"assigned":1,"assignee":{"id":1,"name":"Thomas Z."}},{"id":2,"label":"Cha\u00eene de messagerie (mail)","state":"Correct","state_id":0,"weather_icon":"sun","since":">6j5h","availability":{"current":100,"trend":"="},"acknowledged":0,"assigned":0},{"id":3,"label":"CRM (CRM)","state":"Correct","state_id":0,"weather_icon":"sun","since":">35j","availability":{"current":100,"trend":"="},"acknowledged":0,"assigned":0}]},

Answer №1

Recently started exploring the capabilities of the PrimeNG library and came across the implementation of Promises.

I decided to modify a tutorial to use observables instead, but encountered an error in the process. Here is how I resolved it:

Both HTTP calls were made, with the second one returning an Observable of any type (not TreeNode[]).

getFiles()  {
  return this.http.get<any>('assets/files.json')
  .toPromise()
  .then(res => res.data as TreeNode[]);
}

getFiles2(): Observable<any> {
  return this.http.get<any>('assets/files.json');
}

When outputting from both methods, the issue becomes apparent:

https://i.stack.imgur.com/s7nB0.png

The observable outputs an object containing an array of data called "data", while the promise simply outputs the array.

The solution is to append the data object and ensure that you cast the returned object to TreeNode[]:

 this.dataSvc.getFiles2().subscribe({
    next: files => {
      this.files2 = files.data as TreeNode[];
    }
  });

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

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

Syncfusion Angular TreeGrid Hierarchy connectors and lines for improved data visualization

Is it possible to display guiding lines or connectors that represent the hierarchy of data in a Tree Grid? You can see an example with blue lines in the image below: ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

The argument labeled as 'shop' does not fit the criteria for the parameter 'items' or 'cart'

I've been doing some research but haven't had any luck finding a solution. I'm fairly new to Angular and currently working on a webstore project. I followed a tutorial, but encountered an error along the way. import { select, Store } from & ...

The 'Headers' type does not share any properties with the 'RequestOptionsArgs' type

I have included the necessary headers, objects, and URLs in my code but I keep getting an error message. The 'Headers' type does not have any properties in common with the 'RequestOptionsArgs' type This is my code: getContactData(a ...

Having trouble with obtaining real-time text translation using ngx translate/core in Angular 2 with Typescript

Issue : I am facing a challenge with fetching dynamic text from a JSON file and translating it using the translate.get() method in Angular2. this.translate.get('keyInJson').subscribe(res => { this.valueFromJson = res; /* cre ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

What is the best way to trigger an event within an Angular app using RxJS in version 10?

As I venture into the world of Angular10, I find myself experimenting with a Canvas and honing my skills in drawing on it. Let's refer to the object drawn on the canvas as a "Foobar" - my Angular10 code for drawing Foobars is coming along nicely. Util ...

How can I populate a mat-table in Angular 7 with data stored in an object?

At the moment, my code is set up to populate a table with data. In my component.ts file: import { HttpClient } from "@angular/common/http"; import { Component, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, Validators } from "@angular/fo ...

Acquire data through Reactive Form input

Struggling to populate my entity data in a reactive form. Data retrieval is successful, but unsure about the ideal method and timing for filling out the form with these values. Here's the structure of my form: import { Component, OnInit, Input } fr ...

The HttpPut request code format is malfunctioning, although it is effective for another request

I'm struggling with a HTTPPUT request that just won't get called. Strangely enough, I have a similar put request that works perfectly fine for another tab even though both pages are practically identical. I've exhausted all options and can&a ...

Setting the background color of a button within a template in an Angular 8 component using style.background

I have been exploring the different versions of Angular and their changes. Currently, I am enrolled in an Angular course on Udemy where I have installed Angular 8. In the course, it is mentioned to use style.backgroundColor on a button inside the template ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

Arrange a JSON response in descending order and filter out specific values

Currently, I'm encountering a challenge when trying to extract a specific attribute from my JSON response. The issue arises when I attempt to sort the results based on the `percentage_match` in descending order. Once sorted, my goal is to create an ar ...

Toggle the visibility of a modal in code across various components in an Angular 4 project using Typescript

As I was working on my university App, I encountered an issue while attempting to open a Bootstrap modal in code from a different component. Opening a component in code from the same component posed no problems for me as I use JQuery and it functions perfe ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

Issue: Undefined default value property in TypescriptDescription: In Typescript,

export class EntityVM implements EntityModel { ... Properties... ... constructor(newEntity: EntityModel, isCollapsed = false) { ... Properties... ... this.isCollapsed = isCollapsed; } } public myFunction(myEntity: EntityVM) { / ...

Encountered difficulty retrieving properties from the req.query object within expressjs

My setup includes a router configuration like this: router.get('/top-5-cheap', aliasTopTours, getAllTours); I've also implemented some middlewares: Middleware aliasTopTours: In this middleware, I am setting certain properties on the reque ...

Error: The archived-solution-list.component.html file failed to load due to an unhandled Promise rejection

I am encountering the following error on the console while executing my code. Just so you know, everything was working fine before a minor modification. I would appreciate your assistance in resolving this: Unhandled Promise rejection: Failed to load ar ...

[deactivated]: Modify a property's value using a different component

One of the requirements for my button is that it should be disabled whenever the callToActionBtn property is true. match-component.html <button [disabled]="callToActionBtn" (click)="sendTask()>Send</button> match-component.ts public callToA ...