Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing this problem?

    createPlaylist(token:string = localStorage.getItem('myToken')) {

      const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
      const headers = new Headers();
      headers.append('Authorization', 'Bearer ' + token);
      headers.append('Content-Type', 'application/json');
      const body = {
        'name': 'searchDDD playlist'
      };
      this.http.post(url, body, { headers } )
      .subscribe(res => {
        console.log(res.json().name);
        console.log(res.status);
        this.playlistID = res.json().id;
        this.asd();
      });


    }

    asd(token:string = localStorage.getItem('myToken')){
      const url = `https://api.spotify.com/	v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks?`;
      const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
      'spotify:track:1301WleyT98MSxVHPZCA6M']};
      const headers = new Headers();
      headers.append('Authorization', 'Bearer ' + token);
      headers.append('Content-type', 'application/json');
      this.http.post(url, body, { headers } ).map(resp => {
        console.log(resp);
    });
}

Answer №1

Observables are lazy by nature, so without methods like subscribe() or forEach(), they won't actually execute.

this.http.post(url, body, { headers }).subscribe(response => {
    console.log(response);
});

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

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

Execute different commands based on operating system using NPM conditional script for Windows and Mac

Scenario: I am currently configuring a prepublishOnly hook in NPM. This hook is designed to remove the "lib" folder, transpile the typescript source files into a new lib folder, and then execute the tests. The issue at hand: There are two individuals re ...

Using JavaScript to call an API in PHP and determine how to handle a response that is not equal to 200 by printing an

Greetings! I am aiming for a scenario where, upon clicking the link, the user's parameter is transferred to JavaScript. This parameter will then be used in ajax to trigger a call to my PHP file containing the API. The API, after processing the parame ...

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...

When incorporating Papaparse with Angular 2, encountering the issue "Identifier 'Papa' is not found" may arise

Currently, I am facing an issue in my project where after deleting and re-installing node_modules to resolve errors, the definition of 'Papa' is missing. As a result, when npm updated the node modules again, Angular 2 is unable to find 'Papa ...

Issue with jQuery Master-Detail dropdown list selection

Having trouble isolating the code in this jsfiddle script. Despite my efforts, it seems that isolation is not working as expected and Firebug isn't showing any errors on the console: <!DOCTYPE html> <html lang="en"> <head> ...

Tips for creating a universal function for two interlinked types

My goal is to establish an abstract relationship between different sub-types of Message and Response, allowing for a generic function that takes a Message as input and returns a corresponding Response. Specifically, when the function is called with type Me ...

JSON representing an array of strings in JavaScript

Encountering difficulties when trying to pass two arrays of strings as arguments in JSON format to call an ASMX Web Service method using jQuery's "POST". The Web Method looks like this: [ScriptMethod(ResponseFormat=ResponseFormat.Json)] publ ...

Having trouble upgrading to the newest version of angular-cli on my Ubuntu 14.04 system

I'm currently in the process of updating my angular-cli version by running: npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70111e17051c11025d131c11025d14">[email protected]</a> However, I enco ...

Clicking on an element in React Material UI Autocomplete will bring it

I'm currently working with a material-ui autocomplete element <Autocomplete id="combo-box-demo" autoHighlight openOnFocus autoComplete options={this.state.products} getOptionLabel={option => option.productName} style={{ width: 300 ...

What is the most effective method for obtaining the ViewContainerRef of a mat-row in Angular 4

I am currently working with a mat-table and I'm looking to retrieve the ViewContainerRef of a clicked row in order to add another component within that specific row. Can anyone suggest the most effective method to obtain the ViewContainerRef of a row? ...

Attempting to display the todo item in the form of <li>, however, the todo.name property is not

I am currently developing a task manager application and have encountered a puzzling issue: When I include the Todo component within the TodoList component and pass the todo item as a prop todo = {name: "ssss", status: false, id: 0.0289828650088 ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

I am encountering some difficulties with the functionality of the angularjs dialog

I've been attempting to integrate an AngularJS dialog feature into my application by following the examples provided on material.angularjs.org. However, despite copying everything accurately, I am unable to get it to function. Can anyone help identify ...

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

Tips for patiently waiting for a function that is filled with promises

Consider the following function: const getData = () => { foo() .then(result => { return result; }) .catch(error => { return error; }); }; Even though getData does not directly return a promise, it internally handles asynchro ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

Electron Searching for Files in Main Directory

We have developed a web application using Angular 2, but we are facing an issue when trying to run it as an Electron application. After branching out the solution and making changes to package.json to launch Electron on start, we encountered an unexpected ...