Using Angular to subscribe to a service that employs http requests

I am completely new to angular and typescript, and I'm facing a challenge.

Within my service, I have a function:

login(email: String, password: String) {
  let formData = {
    usuario    : email,
    senha      : password,
    retsession : true
  }

  console.log('go');
  return from(this.nativeHttp.post<any>(this.env.API_URL+'/login', formData, {'Content-Type': 'application/json'})).pipe(
    finalize(() => console.log('ok'))
  ).subscribe(data => {
    console.log('back');
    console.log(data);
    this.token = "123";
  }, err => {
    console.log('Native Call error: ', err);
  });
}

Now, when trying to invoke it from my auth-login.page.ts, like so:

onSubmit(f: NgForm) {
  this.authService.login(f.value.usuario, f.value.senha).subscribe(
    data => {
      console.log('login ok');
    },
    error => {
      console.log('error occurred');
      console.log(error);
    },
    () => {
      this.router.navigateByUrl('/tabs');
    }
  );
}

An error message pops up:

auth-login.page.ts(24,60): error TS2551: Property 'subscribe' does not exist on type 'Subscription'.

What could be the issue?

Answer №1

When utilizing the "subscribe" function, it is essential to create observables and utilize the default "observable" function within this.nativeHttp.post.

For more information, refer to the following link.

Answer №2

I suggest updating your code with the following changes:

return this.nativeHttp.post<any>(this.env.API_URL+'/login', formData, {'Content-Type': 'application/json'})

After making these adjustments, you can keep the rest of your component code as is and everything should work correctly.

onSubmit(f: NgForm) {
  this.authService.login(f.value.usuario, f.value.senha).subscribe(
    data => {
      console.log('login successful');
    },
    error => {
      console.log('error occurred');
      console.log(error);
    },
    () => {
      this.router.navigateByUrl('/tabs');
    }
  );
}

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

Safari is causing issues with HTML5 Video playback

I have a client with a media-heavy website containing numerous video and audio files. While the videos load perfectly on Chrome, Firefox, and IE, they do not load on Safari for Windows. Here's a snippet of the code: <video controls="controls" type ...

Unraveling JavaScript using regular expressions in Python

I need to parse some JavaScript text using Python. Within the JS code, there is a variable like this: this.products = ko.observableArray([#here is some json, #here is some json]) The observableArray can hold a single JSON object like: observableArray({&a ...

The AngularJS module is encountering loading issues

Let me provide some context about my current setup. I am working on Windows7, using StS IDE, pivotal tc server, and Google Chrome. I have developed an AngularJS application. Below is the code for my index.jsp: <%@taglib prefix="c" uri="http://java.sun ...

Function for emptying the cart and Webstorage in JSON format

Currently, I am working on a university project to develop a website for a company looking to sell products online. While creating the shopping cart functionality, I encountered some challenges but managed to implement a 'drag and drop' feature s ...

Issue with Socket IO: It does not function properly with public IP addresses, but it works perfectly on localhost

I've been working with socket io and have successfully deployed the app on my localhost. For client-side connection, I'm using : var socket = io.connect(window.location.origin + ":3333"); To ensure scalability, on the server side I am utilizin ...

How come an <a> tag is nabbing mouse clicks from a <canvas> element?

I have been experimenting with creating a 3D piano using three.js. Here is a snippet of the code I am currently working on: let renderer, camera, scene, light, keys, selectedKey; init(); render(); function init() { // Code for initializing renderer, ...

Tips for altering the color of two circles when they overlap:

Hello, I am interested in creating an effect where two circles change color when they overlap. Specifically, I would like the overlapped section to become white to represent sets. var canvas = d3.select("canvas"), context = canvas.node().getContext( ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...

Error message encountered by novice users of Reactive forms: Unable to access the property 'firstName' as it is undefined

I'm encountering an issue TypeError: Cannot read property 'firstName' when I try to load my Reactive Form. Even though the form is working correctly and my data is being displayed, I still see this error. I have looked at similar questi ...

Issue encountered while creating a token in a JavaScript Chrome extension and attempting to validate it on a backend Node.js server

Trying to create a token within a chrome extension and utilizing it to authenticate requests to the backend server has proven challenging. While successfully generating a token on the front end, encountering an error when verifying it with the google-auth- ...

Tips for using jest.mock with simple-git/promise

I have been attempting to simulate the checkout function of simple-git/promise in my testing but without success. Here is my current approach: jest.mock('simple-git/promise', () => { return { checkout: async () => { ...

What is the process for adding tooltips to ngSelect options? I want the tooltips to appear when hovering over the options in the dropdown menu

<ng-select [items]="cities" bindLabel="name" placeholder="Select city" [(ngModel)]="selectedCity"> </ng-select> Is there a way to include tooltips for ngSelect options? I want to display a toolt ...

Tips on how to export variables that are defined within the .then() function

Hey there! I'm currently working on an Angular application using single spa. Integrating the single spa feature with an existing Angular app involves creating a new main file which is used to start the application. My issue arises when trying to incor ...

Converting a JSON array to C# and vice versa in Xamarin Forms

I've been struggling to send a C# object as JSON array to an API endpoint. I feel like I'm going crazy trying to solve these issues. Here's a sample of the JSON data: Array ( [user_id] => 0002323445635 [order] => {"order":{" ...

Display the respective div when each anchor is clicked

Imagine you have some basic HTML code like this: What I'm aiming to accomplish is opening the corresponding pane for each anchor without needing to check by name. <div class="nav"> <a id="nav1" class="active">Tab 1</a> <a ...

Integrating a packaging NPM functionality into Angular for streamlined development

After completing a software engineering assignment, I am struggling with the final requirement. I need to implement an NPM packaging command called "npm build" to compile and publish the front end developed in Angular to the backend project. Initially, I t ...

The querySelectorAll function will choose all classes that are identical

My calendar design utilizes three different classes to style its child elements: "old day", "day", and "new day". However, I am facing an issue where using querySelectorAll with the class name "day" also captures the other two classes. This becomes problem ...

What is the best approach to implement a gradual loading of data in a FlatList in React Native

I am facing an issue with my flatlist where the renderItem function does not render data properly from my custom backend when the internet connection is slow or if I reload too many times. This results in either the data not appearing on the screen or the ...

What is the best approach to resolving the MongoServerError: E11000 duplicate key error?

Index.Js File: const cookieSession = require("cookie-session"); const express = require("express"); const app = express(); const helmet = require("helmet"); const morgan = require("morgan"); const dotenv = require(&q ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...