Passing headers using a universal method in HTTP CRUD process

My service function is structured like this:

Please note: I am required to work with cookies

  book(data: Spa): Observable<any> {
    return this.http.post(`${environment.apiURL}:${environment.port}/${environment.domain}/abc/my.json`, data,
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });
  }

In each method where I have to send headers, it looks messy and not following the DRY principle. Is there a way to automate this process by writing a generic CRUD service? How can I achieve that?

I attempted the following approach:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { RequestOptions } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor(private http: HttpClient) { }

  post(url, params): Observable<any> {
    return new Observable(observer => {
      const headers = new Headers();
      let options = new RequestOptions({ headers: this.createHeader(headers) });
      this.http.post(url, params, options)
        .subscribe(response => {
          observer.next(response);
          observer.complete();
        }, (e) => {
          observer.error(e);
        });

    })
  }

  createHeader(headers: Headers): Headers {
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return headers;
  }
}

However, an error occurs during compilation on the line

let options = new RequestOptions({ headers: this.createHeader(headers) });

Type 'Headers' is missing the following properties from type 'Headers': keys, values, toJSON, getAll, and 2 more.ts(2740) interfaces.d.ts(61, 5): The expected type comes from property 'headers' which is declared here on type 'RequestOptionsArgs' (property) RequestOptionsArgs.headers?: Headers

Additionally, a warning is displayed:

RequestOptions is deprecated: see https://angular.io/guide/http (deprecation)

Answer №1

experiment

this.http.post(url, data, {headers: this.setHeaders(metadata)})

Alternatively, consider exploring HttpInterceptors for a more standardized header approach

Check out this helpful guide as well

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

Error: Uncaught TypeError - The function indexOf is not defined for e.target.className at the mouseup event in HTMLDocument (translator.js:433) within the angular

Upon clicking on an SVG to edit my data in a modal bootstrap, I encountered the following error: Uncaught TypeError: e.target.className.indexOf is not a function at HTMLDocument.mouseup (translator.js:433) This is my SVG code: <svg data-dismiss ...

Using Angular NgUpgrade to inject an AngularJS service into an Angular service results in an error message stating: Unhandled Promise rejection: Cannot read property 'get' of undefined; Zone:

I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

Encountering an issue with unexpected token 'import' while working on Angular-cli and RC

Currently, I'm in the process of setting up Material 2 with Angular-cli RC5. However, when attempting to load the material button component in app.module.ts, I encounter the following error message. zone.js:461 Unhandled Promise rejection: SyntaxErro ...

Get a file transfer from MVC 5 to Angular 2

After gaining experience in C# backend and ASP.Net MVC, I decided to take on the challenge of learning Angular 2. While most of the experience has been positive, I have hit a roadblock with a simple file download task. Despite studying various examples on ...

Ways to enhance the type definitions for a built-in HTML element in Vue.js?

Imagine having an element that wraps around an input and inherits all of its properties, along with some extras. In React, you would define this as: interface ExtendedInputProps extends React.ComponentPropsWithoutRef<'input'> { some: T ...

Unknown Angular component identified

I'm currently working on an application with the following structure: app |-- author |-- |-- posts |-- |-- |-- posts.component.html |-- |-- author.component.html |-- |-- components |-- |-- tag |-- |-- |-- tag.component.ts |-- home |-- |-- home.comp ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...

Create a functioning implementation for retrieving a list of objects from a REST API

I am looking to incorporate an Angular example that retrieves a list from a REST API. Here is what I have attempted: SQL query: @Override public Iterable<Merchants> findAll() { String hql = "select e from " + Merchants.class.getName ...

Using typescript, import the "anychart" library

After attempting to include the "anychart" library in my .ts file using the following import statement: import 'anychart'; I noticed that this line of code caused the entire HTML page on my local server to disappear. Here is a snippet from my ...

What are the limitations of using concatMap for handling multiple requests simultaneously?

In my current function, I am receiving an array of objects called data/ids as a parameter. Within this function, I need to execute a post request for each element/id: fillProfile(users) { const requests = []; console.log( 'USERS.length:&apos ...

Modify the [src] attribute of an image dynamically

I have a component that contains a list of records. export class HomeComponent implements OnInit { public wonders: WonderModel[] = []; constructor(private ms: ModelService){ ms.wonderService.getWonders(); this.wonders = ms.wonder ...

Creating trendy designs with styled components: A guide to styling functional components as children within styled parent components

I am looking to enhance the style of a FC styled element as a child inside another styled element. Check out the sandbox example here const ColorTextContainer = styled.div` font-weight: bold; ${RedBackgroundDiv} { color: white; } `; This resul ...

Error: Attempting to access the 'subscribe' property of an undefined value (Observable)

In my TypeScript/Angular2/SPFx project, I have the following code snippet: // Populate the regulatory documents dropdown this.regulatoryDocumentsService.fetchRegulatoryDocumentsData().subscribe( data => { this.regulatoryDocumentsData = data }, ...

Can someone explain why the Next 13 API route is showing up as empty?

I am currently working with Next 13 and I am attempting to create a simple API route. My goal is to have a: "hi" returned when I visit localhost:3000/api/auth. Despite not encountering a 404 error or any errors in the terminal or console, I can&a ...

Challenges transitioning syntax from Firebase 4 to Angularfire2 in Angular 4

Currently, I'm in the process of updating my Angular 2.3.1 and Firebase 2.x.x project to the newest version. However, I'm encountering difficulties with syntax and imports. I've been exploring resources like https://github.com/angular/angula ...

Create a keyup function that triggers an alert message if the user's input does not meet the

Hello, I'm looking for some assistance with a coding problem. Basically, I have an array of numbers which includes 5, 8, and 10. I need to create a form where users can input numbers. If the user inputs a number that is not 5, 8, or 10, I want to disp ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

Exploring Attack on Titan alongside the concept of dynamic route templates in coding

I am currently working on creating a factory for an UrlMatcher. export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy'); export const routes: Routes = [ { matcher: dummyMatcher, component: DummyComponent }, { path: &apos ...

Despite subscribing, the Ngxs @Select decorator is still returning undefined values

I am attempting to access and read the labels stored in the state file. Displayed below is my state file: export class LabelStateModel { labels: LabelConfig = {}; } @State<LabelStateModel>({ name: 'labels', defaults: { labels: { ...