Unable to find a solution to Angular response options

I'm having trouble saving an item to local storage when receiving a 200 response from the backend. It seems like the request status is not being recognized properly.

    options = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Access-Control-Allow-Origin': '*',   
      'Authorization': 'Bearer '+localStorage.getItem("access_token")
    }),
    observe: "response", // ensuring full response is displayed
    responseType: "json"
  };


  
  constructor(private http: HttpClient, private router: Router) { 
   }
  
  authenticate(url, data, options) {
 
      this.http.post(environment.getBaseAddress() +url+'/', data, options).subscribe((data:any) =>  {
        if (data.status == 200) {
        localStorage.setItem("access_token", data['access_token']);
        console.log(data.status)
        }
        else this.router.navigateByUrl('something-else');
        })

      
    }

Answer №1

When the next function within the subscription block is executed, it indicates a successful API call. You do not have to explicitly check the status code in this case, as an alternate approach you can use:

this.http.post(environment.getBaseAddress() +url+'/', data, options)
    .subscribe((data:any) => {
       localStorage.setItem("access_token", data['access_token']);
    }, (err) => {
       this.router.navigateByUrl('something-else');
    });

Learn more about subscription callbacks.

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

Angular 2 - Dragula for ng2

<div *ngFor="let col of columns"> ... <div [dragula]="'tickets-list'" [dragulaModel]="col.tickets" (drop)="onDrop($event, col)"> <ul> <li *ngFor="let ticket of col.tickets"> {{ ticket }} </li ...

"Troubleshooting: Issue with updating page CSS in browser when using npm, node-sass, and concurrent in an

Embarking on a new Angular2 project to enhance my skills, I've made the decision to avoid Yeoman Generator and tools like Grunt or Gulp due to the software still being in development. Instead, I'm utilizing the Node Package Manager to run automat ...

Transferring data from the server to the client side in Next JS with the help of getInitialProps

I am currently developing an application using nextJS. Within server/index.ts, I have the following code: expressApp.get('/', (req: express.Request, res: express.Response) => { const parsedUrl = parse(req.url, true); const { query } = ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

When you use map to transform the value, Observable will consistently return as undefined

Can anyone help me figure out why, when I transform the observable, it returns undefined in the console log even though there are assigned values? HTTP Request getLibraryCardPeople(bookName: String): Observable<people[]> { return this.http.get<Li ...

TypeScript class featuring a unique method that is not utilized in every instance

I have a TypeScript class that is managing ZMQ bus communication. Initially, I created a general class that can be instantiated multiple times. However, now I need to create instances with slight variations that do not perfectly fit the generic class I o ...

You won't find the command you seek within the confines of "tsc."

Whenever I type tsc into the terminal (regardless of location), I am met with the following message: $ npx tsc --version This is not the tsc command you are looking for In order to access the TypeScript compiler, tsc, from the command li ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...

How to Retrieve the Access Token from Instagram using Angular 2/4/5 API

I have integrated Instagram authentication into my Angular 2 project using the following steps: Begin by registering an Instagram Client and adding a sandbox user (as a prerequisite) Within signup.html, include the following code snippet: <button t ...

Problem Encountered with Inaccurate Binding of Dynamic Form Control Values in Angular

UPDATE: Follow this link to access the editor for my Stackblitz application, which demonstrates a simplified version of the issue regarding the "transfer" of value between the first and second controls. I am currently developing a dynamic form in Angular ...

performing resolver when needed in angular version 5

I have been working on a project using Angular and recently updated it from version 4.2 to Angular 5. Although I haven't utilized any new features introduced in Angular 5 yet. My current task involves executing a resolver on a specific route when a c ...

What do you think about gulp-typescript and the latest @types typings for TypeScript?

I've added @types/jasmine as a development dependency. This is my gulp task for compiling TypeScript: gulp.task('compile:tests', ['compile:typescript', 'clean:tests'], function () { var project = ts.createProject(&a ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

Get your hands on the latest version of Excel for Angular

214/5000 I am currently facing an issue in Angular where I am attempting to generate an excel file. Within the file, there is a "Day" column that is meant to display numbers 1 through 31. However, when attempting this, only the last number (31) is being pr ...

Tips for addressing style issues within innerText

I am trying to use PrismJS to highlight HTML code, but the inner text function doesn't recognize line breaks (\n). <pre class="language-markup background-code"><code [innerText]="getHtmlCode()""></code> I have been working wi ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

Angular Dynamic Alert Service

Is it possible to customize the text in an Angular Alert service dynamically? I'm looking to make certain words bold, add new lines, and center specific parts of the text. Specifically, I want the word "success" to be bold and centered, while the rest ...

Troubleshooting CORS problem: Angular 2 and AspNetCore WebApi encounter error with preflight response having invalid HTTP status code 401

Hello there! I am currently working on implementing a straightforward token based authentication method in an Angular 2 RC6 application against an AspNetCore WebApi project that I developed using Visual Studio 2015. If you're interested, I have uploa ...

Tips for transforming a Json array into an object in Angular 5

I am working with a Json array that looks like this: [{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}} ,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}} ...

The Access-Control-Allow-Origin CORS header does not align with the null value on the Ajax request

Encountering the same issue in my browser Cross-Origin Request Blocked: The Same Origin Policy prevents access to the remote resource at http://abc-test123.com/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’). My ...