Populate landing page with information retrieved from a REST API using Angular 6 Interceptor

To display data on the home page from a REST API using Interceptor in Angular 6, authorization with 'username' and 'password' is required. Previously, I successfully fetched data using Node.js. However, after switching to the Interceptor, an error occurred:

ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at subscribeTo (subscribeTo.js:41)
at subscribeToResult (subscribeToResult.js:6)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub (mergeMap.js:70)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext (mergeMap.js:67)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next (mergeMap.js:50)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at Observable._subscribe (scalar.js:5)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:42)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:28)
at MergeMapOperator.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call (mergeMap.js:28)

The landing component function I created is as follows:

const userData = { username: 'anonymous', password: '' };

this.http
  .post(`${this.baseURL}/auth/jwt/authenticate`, userData)
  .subscribe(res => {
    // console.log(res);
    const token = JSON.parse(res['_body']).token;
    this.publicToken = token;
    if (token) {
      this.publicTokenStatusListener.next(true);
      localStorage.setItem('public-token', token);
    }
  });

The Interceptor code snippet is shown below:

intercept(
        req: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {

const authToken = localStorage.getItem('public-token');

        
const copiedReq = req.clone({
    params: req.params.set('auth', authToken)
});

return next.handle(copiedReq);

}

Although I'm returning the GET request for REST data from the service to fetch the observable, it's not functioning as expected.

I can retrieve the 'token' in the Interceptor. Any suggestions would be greatly appreciated.

Thank you in advance.

Answer №1

HttpParams is considered to be immutable.

It is recommended to utilize the setParams method instead of directly using params:

const updatedRequest = request.clone({
    setParams: {'auth': userToken}
});

Have you carefully thought about whether sensitive information should be sent as params?

Perhaps it would be more secure to pass this data in the headers instead?

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

The issue with AngularJS array filtering remains unresolved

How can I get this filter to function properly? <div ng-repeat="rvs in reviews | filter:{ Name:'{{ r.Name }}' }"> {{ rvs.Name }} </div> 'r.Name' is retrieved from another array "r in restaurants" However, instead of usin ...

Different Ways to Remove an Element from an Array in TypeScript

I have been browsing through the responses here, but none of them seem to work for me. I am trying to remove an item from an array, but no matter what I do, the index keeps returning as -1. deleteItinerary(id: string) { this.dataSvc.removeItinerar ...

Transform a PNG image with transparency into a JPEG file using imagemagick

Consider utilizing the imagemagick npm module for your image manipulation needs. In the task of converting a .png file with a transparent background to a .jpeg with a white background, you may encounter challenges. Here is an example: const ImageMagick ...

Ways to establish cache in a server-side next.js environment

Having issues with 'node-cache' implementation in my Next.js backend. Below is the code for my cache file: cache.ts import NodeCache from 'node-cache'; const Cache = new NodeCache({ stdTTL: 60 * 60 * 6 }); // 6 hours export default Cac ...

Setting up Linter and Prettier to enforce rules in HTML

My team and I in our Angular project have established certain rules regarding template formatting and Sass stylesheets. We utilize linter and prettier within our project. I am now curious if there is a way to configure these tools to automatically enforce ...

Automating the process of texture mapping with Three.js

I am looking for a solution to automate texture mapping on a mesh. In the scenario depicted in the image, I have applied a single texture (1024 X 1024 pixels) to two cubes, each with different surface areas. The texture appears resized for both cubes due ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...

Show the message "Server is now active on port 5000" in the console but unfortunately cannot retrieve it

The backend API has a specific template that can be viewed here. Below is the code snippet for the backend: index.js import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; import ...

KnockoutJS's data binding feature is failing to display any content within the table rows

My JavaScript function creates a model and applies it to an HTML document using knockoutJS. In the HTML file, I have two different ways of displaying the same data: 1- A select list (which is working fine) 2- A table (not showing the same data) I need a ...

Creating an object from multiple lines read from files and sending the response using nodejs sendFile: A step-by-step guide

I have a server where I am logging messages to files. The client needs to download these files, but when there are multiple messages in a file, it throws an exception on the client side due to invalid JSON. I have provided an example of how the file data l ...

Background PHP/JS authentication through HTTP

Recently, I developed a PHP website that includes embedded web-cam snapshots which refresh every 2 seconds using JavaScript. For the first camera, I can easily log in using URL parameters like this: cam1-url?usr=usr&pwd=pwd. However, the second camer ...

Exploring beyond zero

In the image below, I am able to retrieve data from [0] using the following Node.js code snippet: const stockxAPI = require('stockx-api'); const stockX = new stockxAPI(); stockX.searchProducts('yeezy', { limit: 1 }) .then(products ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

Using a promise inside an Angular custom filter

I am attempting to implement a filter that will provide either a success or error response from the ret() function. The current code is returning {}, which I believe is its promise. .filter('postcode', ['$cordovaSQLite', '$q' ...

How to Submit a Form Using Jquery

Is it possible to submit a form using JQuery without the need for page reload? A Sample Form: <html> <form method="post" action="submit.php"> <input type="text" name="name"/> <input type="submit" name="submit" value="submit"/ ...

JavaScript - Ways to retrieve the date in the desired format

Looking to display the Date output in 2 different formats. Below is my current attempt: <p id="demo"></p> <script> var d = new Date(day, month); document.getElementById("demo").innerHTML = d.toString(); </script> Unfortunately, t ...

I seem to be having issues with the downloaded files for Bootstrap 4. Is there something I am

After creating a site with Bootstrap 4 and downloading all the necessary files, I encountered an issue where Bootstrap was not functioning properly. Strangely, when using the CDN version of Bootstrap, everything worked perfectly. Could I be overlooking som ...

While performing compilation, Angular's ngFor triggers an error when used with SVG elements

I am attempting to create a recursive function of lines in order to generate a graph, but I am encountering a strange error in the console. It works fine on node.js. Below is the code snippet: <svg height = "200" width = "300"> ...

Employing JavaScript to set a variable that changes dynamically

In my code, I have a functionality that allows for changing different dropdowns with similar ending IDs. In other parts of the code, I have assigned variables rl and rl_extra as well as rs and rs_extra. Now, when the var prefix is determined to be either ...

What is the process of inserting binary data into mongoDB along with an objectId?

I'm trying to add a document to a collection that requires an ObjectId and a BinData value, but I'm not sure how to do it. When I attempt to execute this code, I receive the following error: TypeError: Cannot read property 'ObjectId' o ...