Troubleshooting a Missing Call Display Issue in Angular2 API

Greetings, I am a new web developer and I have been tasked with creating a prototype Inventory Page using Angular2. Please bear with me as my code may not be perfect.

In the snippet below, you'll notice that we are calling our base back-end API ('?') from the EXAMPLEapi.service page. This call is then passed to an ngOnInit function within EXAMPLEapi.component to initialize the inventory on the page.

Once the initial inventory is loaded, users should be able to select various filtering values such as Min/Max Years, Mileage, colors, etc. These values are captured by the form in EXAMPLEapi.component.html and sent to the refreshInv() function in EXAMPLEapi.component. The function converts these values into parameters using URLSearchParams before making another call to the API.

The structure of the API allows us to simply append 'min_price=' at the end of the base URL to reflect changes in the inventory call.

However, despite receiving a successful status 200 network response when submitting the filters, the inventory does not load back onto the page. It remains blank for some reason.

EXAMPLEAPI.service.ts

// Code from EXAMPLEAPI.service.ts is provided here

EXAMPLE.component.ts

 // Code from EXAMPLE.component.ts is shown here

Answer №1

To begin with, if you are looking for guidance on setting up an angular2 plnkr using unpkg, you can find an example here.

In regards to your code, the function refreshInv currently returns a subscription, which serves no purpose other than to unsubscribe.

I would like to propose an alternative approach that has proven effective for me and will streamline your code. The data flow in your scenario is: 'query' -> 'request' -> 'display'. In rxjs, this can be easily implemented as follows:

let items$ = jsonParams$
  .map(urlParamsMapper)
  .switchMap(urlParams => http.get(baseUrl, urlParams))
  .map(response => response.json().data);

Here, urlParamsMapper takes a JSON-based query and converts it to URLSearchParams.

The jsonParams$ observable (in this case a Subject) can be updated with the relevant query details as needed:

let jsonParams$: Subject<any> = new BehaviorSubject({
  min_price: '',
  max_price: '',
  ...
  ext_color: ''
});

Each time the params are updated, the new JSON is constructed and then:

jsonParams$.next(currentParams);

Note: In rxjs 4, use onNext instead of next.

This will trigger the entire chain for you.

The final step of binding it to your template will look something like this:

<my-item-renderer *ngFor="let item; of items$ | async;" [item]="item"></my-item>

Note: Use async to bind to an observer.

If you wish to maintain your service architecture, keeping the HTTP call within a service, you can organize it as follows:

In the service:

createItemsLoader(jsonParams$: Observable<any>): Observable<Array<any>> {
  return jsonParams$.map(urlParamsMapper)
    .switchMap(urlParams => http.get(baseUrl, urlParams))
    .map(response => response.json().data);
}

And in your component:

let jsonParams$: Subject<any> = new BehaviorSubject({min_price: '' ...});
let items$ = ItemsService.createItemsLoader(jsonParams$);

refreshInv() {
  .... let jsonParams: any = construct json params ....
  this.jsonParams$.next(jsonParams);
}

Reactive programming's beauty lies in building your pipelines effectively so that sending new data down the right pipe automatically delivers it to whoever is listening at the other end. Unlike the procedural mindset shown in your initial code snippet.

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

Would it be frowned upon to rely on store instead of data binding for inter-component communication when accessing my data?

Within my current framework, I house the primary business logic within selectors and effects. Components are able to request data by triggering an action that queries the necessary information through selectors. Apart from instances where *ngFor is utili ...

The issue arises when attempting to apply a class binding to the mat-card element, as the mat-card class

When a single class binding is applied to mat-card, the mat-card class does not bind. <mat-card cdkDropList [className]="getClassName(item)"><!-- some content--></mat-card> In this scenario, the class name appears as something ...

Should the method of creating a Dropdown with Angular be considered a poor practice?

I've recently dived into Angular and successfully created my first dropdown using it, which is working great. However, I'm a bit concerned about the number of comparisons being made and wondering if this approach is considered bad practice. The ...

AngularMap with mapping as the value

Can I implement a Map<string, Map<string, number>> collection in my Angular project? I attempted to create and initialize the variable, but encountered an error when trying to set values. Here is an example: //define variable public players: M ...

Passing a click event from a route-outlet to app.component in Angular 2

I'm brand new to using Angular 2 and developing an application app.routing.ts const appRoutes: Routes = [ {path:'', component:HomeComponent}, { path: 'login', component: LoginComponent }, { path: 'register&ap ...

What is the reason behind RematchDispatch returning a `never` type when a reducer and an effect share the same name?

Recently, I made the switch from TypeScript 4.1.2 to 4.3.2 with Rematch integration. Here are the Rematch packages in use: "@rematch/core": "2.0.1" "@rematch/select": "3.0.1" After the upgrade, a TypeScript error p ...

Ways to create a method that can be overridden

Is there a way to declare a virtual method in TypeScript? I'm attempting to achieve something similar to the following: export abstract class SuperClass { public virtual enable(enableComponents: boolean): void { } } ...

Running pre-commit eslint autofix but encountering errors that do not exist

Encountering an issue with committing changes to a file due to a failed pre-commit eslint --fix task, displaying the following errors: × eslint --fix: C:\Users\user\source\repos\project\project-frontend\src\compone ...

Error: Unable to access properties of null (specifically 'writeValue')

My goal is to retrieve an object by its ID, and if the object does not exist, the component will then register the object. However, when the object does exist, it retrieves the object normally, but then throws the same error again. HTML: <div class="c ...

Having trouble with the npm Fluid Player installation

I am attempting to integrate Fluid Player into my Angular application Using - npm i fluid-player However, I'm encountering this error ...

Is there a way to retrieve the headers from the error callback when using the subscribe function?

When a user creates a post, I need to handle any error responses from the server that may occur. The post creation occurs in the UserService's createUser() method. Any errors are caught using the catch method and a new error is thrown. It is important ...

Utilize a dynamically defined union type to create a versatile callback function

I'm currently working on creating a message subscription function. A basic version without types is shown below: function createMessage(message) { postMessage(message) } function addSubscriber(messageType, callback) { handleNewMessage(message =&g ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

angular 6 httpclient include login information in the URL

When attempting to make a HTTP GET request from an Angular 6 project to a CouchDB, I encountered a 401 Error "You are not authorized to access this db." despite passing the credentials in the URL. Below is the code snippet: var url = "http://user:passwor ...

limitation on pairings of two generic types

How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"? For example, consider the following function: function myFunction(options: {x: number, y: string}){ } Now, let's say we have anot ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

What is the best way to implement a dynamic templateUrl for an Angular 2 Component?

My goal is to dynamically load a component's templateUrl based on a value passed from the parent component. I understand that this can be achieved by using property binding to pass the value through @Input. Below, I have provided an example where the ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

Discovering class methods in typescript

Currently, I am running TypeScript unit tests using Mocha Chai after configuring the compiler options to ts-node. Within one of my unit tests, I am seeking a way to retrieve all methods from a utility class that I have designed and execute the same set of ...

What is the purpose of the .Class method in ng.core.component within ES5?

ng.core.Component({ selector:'myapp', template:'<h1>Hello World</h1>' }). Class( { constructor:function() } ); ...