Angular2 encounters an error when processing a custom HTTP request

I offer two unique services

Custom HTTP client service

 fetch(url):any{
  this.storage.fetchData('auth-token').then((token) => {
    let headers = new Headers();
    this.prepareHeaders(headers);
    return this.http.fetch(url+"?token="+token, {
      headers: headers
    });

});

Furthermore, I provide the following service:

  constructor( private _customHttpClient:CustomHttpClient){}

  getVehicles():Observable<any>{
   return this._customHttpClient.get(this.vehiclesUrl+"fetch-vehicles")  
       .map(result => result.json().data)  //encounters an issue

  }

Unfortunately, customers have reported that the second service encounters an error mentioning "cannot read property map of undefined"

Answer №1

It appears that the get(url) method in your code does not actually return anything, causing the issue you are facing.

Furthermore, it is important to avoid explicitly specifying the any type unnecessarily. By letting the compiler infer the return type (which would be void), you can prevent errors like this from occurring. Explicitly stating the return type as any interrupts the type inference process without justification.

While many Angular examples may make use of such practices, they do not necessarily reflect best practices for TypeScript coding.

If the reference to http in your initial service pertains to the official Angular 2 http service, a better approach would be:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap';

export class HttpClient {
  get(url: string) {
    const headers = new Headers();
    this.createGeneralHeaders(headers);

    return Observable
      .fromPromise(this.storage.get('token'))
      .flatMap(
        name => this.http.get(`${url}?access-token=${name}`, {headers})
      );
  }
}

In your original scenario, the get function was not returning any value. Modifying it to return the result of the then call would yield a Promise to an Observable, instead of directly returning an Observable. Since the consuming code seemed to expect an Observable due to the subsequent map invocation, using Observable.fromPromise can achieve the desired outcome easily.

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

Peer dependency conflict detected (while executing ng update @angular/core) - explanation provided

Currently, I am in the process of upgrading my Angular project to version 11.0.5 by executing the command provided below: ng update @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066569746346373728362833">[email ...

Is there a way to preselect the date in the input field as the default?

<mat-form-field> <input matInput [matDatepicker]="picker1" placeholder="From date: mm-dd-yyyy" name="from_date" [(ngModel)]="callListRequestOb.from_date" maxlength="150"> ...

Retrieve user roles from core in Angular prior to implementing a guard

Hey, I'm facing an issue with my app.module setup. I have implemented lazy loading to load the core module and store roles in the core component. Everything works fine when I navigate from one page to another with the role guard applied. However, when ...

Angular 7: Exploring the Best Way to Modify Query Parameters While Subscribing

When attempting to convert query parameters to integers within a subscription, I am encountering an issue where the code stops executing after any transformation of query parameters. This occurs regardless of whether the parameters are transformed to integ ...

Using Angular 2's ngModel directive to bind a value passed in from an

Using [(ngModel)] in my child component with a string passed from the parent via @Input() is causing some issues. Although the string is successfully passed from the parent to the child, any changes made to it within the child component do not reflect bac ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Dynamic Angular routes with varying numbers of parameters

I am working on developing an application where I need to associate TreeList navigation with routes. Consider the file structure in the explore section: - desktop - file1.txt - pictures - wallpaper - my-selfie.png - file2.txt - file4. ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Utilizing a single Angular 2 app to incorporate various components on a single page

Can you guide me on how to dynamically render a section of HTML from a child component to a parent component in Angular 2? The concept is to create a main layout where different sections can be replaced or customized by child components based on specific r ...

Embed the getServerSideProps function within a helper method

I have multiple pages that require protection using firebase admin methods: const getServerSideProps = async (ctx: GetServerSidePropsContext) => { try { const cookies = nookies.get(ctx); const token = await firebaseAdmin.auth().verifyIdToken(c ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Collaborate on Typescript Interfaces within a Firebase development environment

I've been developing a Firebase project using Angular for the frontend, and incorporating the @angular/fire library. Within this project, I have created multiple interfaces that utilize firebase and firestore types. For example: export interface ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

A guide on dynamically displaying a component within another component using Angular2

I am currently facing a challenge where I need to dynamically display a component within another component. When a particular record is clicked, I want to replace that record with the selected component and perform specific actions on it. Does anyone have ...

Using a custom validator in Angular that accepts an array as input

My special code: <input mdInput [mdAutocomplete]="auto" [(ngModel)]="formData.areaName" (keyup)="updateFilteredAreas(formData.areaName)" class="form-control {{areaName.errors ...

The BullMQ library is optimizing performance by efficiently managing Redis connections

Currently, I'm in the process of implementing logic to efficiently reuse redis connections with bullMQ by referring to this specific section in the bullMQ documentation. My setup involves utilizing the latest BullMQ npm version (1.80.6). As per the ...

Incorporating two components and nesting one within the other, similar to the way angular-material seamlessly integrates its components

I recently discovered the angular-material module and I'm a bit perplexed about how it allows multiple components to be used inside one another in the same place. Take a look at the example below: <mat-drawer-container class="example-container"> ...

Managing unpredictable fields within a TypeScript interface Let me known if you need further assistance

Currently, I am developing a web application using Angular and encountered an issue with the JSON data returned by a service call. The problem arises when the mapped JSON contains an Object within one of the fields with unpredictable content. How can I han ...