I'm currently facing issues with the API not returning the list of users to my Angular client application. As I am still in the early stages of learning Angular, I am

Upon inspecting the Network tab, I noticed that one of the users is highlighted in red indicating an error. The console also displays an error 401, indicating unauthorized access. Below is the code snippet from the memberService.ts and member-list-component.ts files. Interestingly, there are no compilation errors.

memberService.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { environment } from 'src/environments/environment';
import { Member } from '../_models/member';

const htttpOptions ={
  headers: new HttpHeaders({
  Authorization: 'Bearer'+JSON.parse(localStorage.getItem('user')).token
  })
}
@Injectable({
  providedIn: 'root'
})
export class MembersService {
  baseUrl = environment.apiUrl;

  constructor(private http: HttpClient) { }
  getMembers()
  {
    return this.http.get<Member[]>(this.baseUrl+ 'users', htttpOptions);
  }

  getMember(username :string){
    return this.http.get<Member>(this.baseUrl + 'users/' + username, htttpOptions);
  }
  
}

member-list-component.ts

import { MembersService } from './../../_services/members.service';
import { Component, OnInit } from '@angular/core';
import { Member } from 'src/app/_models/member';

@Component({
  selector: 'app-member-list',
  templateUrl: './member-list.component.html',
  styleUrls: ['./member-list.component.css']
})
export class MemberListComponent implements OnInit {
  members: Member[];

  constructor(private MemberService: MembersService) { }

  ngOnInit(): void {
    this.loadMembers();
  }
  loadMembers()
  {
    this.MemberService.getMembers().subscribe(members=>{
      this.members = members;
    })
  }

}

Although Postman successfully returns a list of users, indicating that the API is functioning correctly, my client-side application seems to encounter authorization issues. This discrepancy is puzzling and requires further investigation.

For more details, refer to the screenshots below:

Console Tab: Console Tab Screenshot

Network Tab Information 1.0: Network Tab Information 1.0 Screenshot

Network Tab Information 2.0: Network Tab Information 2.0 Screenshot

Postman Results: Postman Results Screenshot

Answer №1

let httpSettings ={
  headers: new HttpHeaders({
  Authorization: 'Bearer '+JSON.parse(localStorage.getItem('user')).token
  })
}

Revise your httpSettings in a similar manner as shown above.

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

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

Error: Select dropdown placeholder malfunctioning

Even after trying numerous solutions from various forums, I am unable to make the placeholder display in my code. Maybe a fresh perspective can help spot what I might be missing. view image here I have experimented with using "" as the value, as ...

The issue at hand in Ionic 2 / Angular 2 is that the NPM module is being utilized as a value instead of referring to a type

I'm currently working on integrating the npm module "ajv" into my Ionic 2 (Angular 2) project. You can find more information about this module at . After running "npm install ajv --save", I proceeded to make some modifications to my app.modules.js fi ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Guide on utilizing map function and reassigning the value

I am facing a challenge with a list of books that have IsEnable defaulting to False. During onInit(), I need to check each book to see if it is enabled. I was considering using an rxjs map and calling the getEligibleBooks() function within the map, but I ...

What is the best way to access Passport.js user information on the client side?

Currently, my application utilizes Angular2 on the front-end, which is served by a separate backend server running express. This back-end server also uses passport.js for Google Oauth authentication. Once a user is authenticated through Passport (using Go ...

The query fails to retrieve results for the specified date and the beginning of the month

I have encountered an issue with my query that is supposed to fetch values between the start and end of the month. Interestingly, when a record is entered on the first day of the month, it doesn't get returned in the query result. Only records entered ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...

Ngb-xx is not a recognized chemical property

Attempting to implement ngb bootstrap in my Angular project has been challenging. Errors keep popping up for every ngb component I try to use. https://i.sstatic.net/jF1xV.png Here's a glimpse of my package.json: https://i.sstatic.net/utqX6.png and ...

"Parent component is unable to modify the value of a child input field when ionViewWillEnter is

Scenario: Main page linked to subpage. Subpage accesses input data from main page. Upon navigation, main page updates variable in ionViewWillEnter. However, this change is not reflected in the subpage. Interactive Demo: https://stackblitz.com/ed ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

How to use TypeScript to set a value in ng2-ckeditor

I have implemented two ckeditor instances using *ngFor: <div class="form-group" *ngFor="let lang of languages"> <span>Legal text in {{lang.translate}} {{lang.abbr}}</span> <ckeditor id="{{lang.abbr}}" formControlName="{{lang.abbr} ...

How can I display the output of an API request in an Ionic 4 app's HTML page?

I have encountered an issue in Ionic 4 where I am able to successfully retrieve the results of a get response, but I am unsure how to display this data on my html page. Within my license.page.ts file: ngOnInit() { return this.httpClient.get(`${this ...

The React Native Flatlist encountered an error due to a mismatch in function overloads

I'm currently working on a React Native app using Typescript, and I've encountered an issue with the Flatlist renderItem function. As someone who is new to both Typescript and React Native, I received the following error message: No overload ma ...

Utilizing React (or Angular) in conjunction with JWT Authentication and managing Sessions/Cookies

My server-side application implements JWT authentication with a React front end (although Angular could also be used for the purposes of this question). Upon initial login, the app exchanges the user's provided username and password for a JWT token t ...

When attempting to open a form in edit mode, data binding fails to work across multiple form controls

When clicking on the edit button, data is loaded into the form using [(ng-model)], however, it seems to be working correctly only for some fields and not all fields. The data is displayed in only a few fields despite receiving data for all fields. Below is ...

Enhancing the visual aesthetics of KendoUI Charts through custom formatting

I've been working on a custom visual to showcase some formatted values. After formatting the text and creating a visual, I expected to see the new values displayed. However, the values remain unchanged. Below is my code snippet: valueAxis: { labels ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...