Please anticipate the reply from the AngularJS 2 API

I want to insert a token into a cookie, but the issue is that the cookie is created before receiving the API response. How can I make sure to wait for the response before creating the cookie?

My Implementation:


getLogin() {
    this._symfonyService.login(this.user,this.pass).subscribe(
        data => {
            this.results = data; 
        },
        error => {
            console.log("Error in HTTP Post Service");
        }, 
        () => {
            console.log(this.results['token']);
            if(this.results['token'] !== "") {
                let token = this.results['token'];
                this.deleteCookie("Cookieteste");
                this.setCookie("Cookieteste", token, 1);
            }
        });
}

Answer №1

try using data instead of () final function

fetchData()
{
this._symfonyservice.fetch(this.user,this.pass).subscribe(//make the request
data => {
            this.results = data
            if(this.results['token']!="")
            {
                let token = this.results['token'];
                this.deleteCookie("Cookieteste");
                this.setCookie("Cookieteste",token, 1);
            }       
        }, // store the response in our variable
                error => console.log("Error fetching data"), // show error message if request fails
                () => console.log('completed')//execute this code regardless
     );

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

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

What is the process of playing blob videos (avi, mov) in Angular14?

I've been struggling with this issue for quite some time without knowing how to resolve it. After some research, I came across a similar question: how to play blob video in angular. However, the problem is that the demo provided in the answer does no ...

There is no value stored in the Angular BehaviorSubject

My attempt at creating a web-socket-client involved organizing all server messages into a BehaviorSubject. Here's the snippet of code: export class WebSocketConnectionService { public ResponseList: BehaviorSubject<WebSocketResponse> = new Be ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

Using Typescript for defining regular expressions as enum values

When making API calls from an API in typescript, I want to clarify how the response should look by using an interface. One particular value is a string that can only have specific values. Isn't this what enums are for? The possible values are: " ...

Saving the authenticated user's information from Firebase (including first name, last name, gender, and more) directly to our database

I am utilizing firebase authentication for user registration and login. Upon registration/login, I aim to save additional user details (such as FirstName, LastName, Gender, etc.) in my database. Currently, I have a process in place to achieve this. Howeve ...

An issue with the HTTP GET Request method is that it often sends "?" instead of "/"

I have a general method for interacting with my Swagger API: get<ReturnType>(url: string, params?: HttpParams): Observable<ReturnType> { return this.http.get<ReturnType>(environment.apiUrl + url, { params: params, }); } ...

Exclude the use of ':any' in React component

Currently, I am new to React and facing a challenge in sending a variable and function to my component. I understand that using :any is not the best practice, so I am seeking a better solution. I am working on creating a modal and passing data to my compo ...

Is it possible to merge arrays of angular modules together?

I have a challenge where I am attempting to merge two arrays of ngx modules and export them as a unified array. Here is an example of what I'm trying to achieve: @NgModule({ declarations: [], exports: [ CommonModule, FormsModule, ReactiveForm ...

Tips for incorporating a fresh attribute into a class through a class decorator

Looking to add a new property to a class using a class decorator? Here's an example: @MyClassDecorator class MyClass { myFirstName: string; myLastName: string; } // Need to achieve something like this: function MyClassDecorator (target: any ...

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...

Error in Angular 2: Component unable to locate imported module

I'm facing an issue where a module I want to use in my application cannot be found. The error message I receive is: GET http://product-admin.dev/node_modules/angular2-toaster/ 404 (Not Found) The module was installed via NPM and its Github reposito ...

When communicating between a different domain and Node.js using Apache's mod_proxy during an AJAX session

I have set up an Apache proxy to forward my api.example.loc to localhost:8080/api ServerAdmin <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c4b595e515d4f48594e7c59445d514c50591250535f">[email protected]</a> Ser ...

Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requi ...

The property is not found in the '{}' type but is necessary in the type... Typescript connect strategy

Hello, I am currently trying to establish a connection pattern for React with TypeScript. I have a reducer set up as follows: type State = { version: number, a?: string } interface ActionC { type: string payload?: number } type IAction = Action ...

What methods can I use to guarantee that a cloned HTML element retains a specific property during Unit Testing?

During my HTML cloning process, I am using the following code snippet: var clone = document.getElementById('tempID').cloneNode(true); After creating the clone, I need to modify its ID by assigning a new unique identifier with clone['id&apo ...

Prevent touching the pseudo content of an element

My issue involves a toggle button component where I have utilized the ::before pseudo class to add text. The problem arises when clicking on the text within the toggle button causes the button's state to change. How can this be prevented? Here is the ...

Set the default page for the p-table

My English proficiency is lacking. I am currently using a p-table with pagination, but I need to modify the pagination in the HTML code. <p-table #dt [columns]="cols" [value]="values" [paginator]="true" [rows]="10" (onFilter)="filtra ...

Using Ionic/Angular ion-datetime with specific conditions

In my Ionic app, I have a datetime picker where users can select a time, but with one condition: If the hour is equal to '21', then the minutes must be set to '00' (not '30'). For all other hours, the minutes can be either &ap ...

Error in Angular deployment: The property "apiUrl" is missing from the object type {production: boolean}

After developing an Angular 7 App with a Laravel backend, I encountered an error while trying to build and deploy it for production. src/app/services/user.service.ts(10,32): error TS2339: Property 'apiUrl' does not exist on type '{ product ...