What steps can be taken to address the issue of the error message: Property 'subscribe' is not recognized on type 'void'?

I encountered an issue while developing a login form in the method "subscribe" under the submit function in the provided code snippet. The error message states: Property 'subscribe' does not exist on type 'void'. How can I resolve this problem? The code segment is outlined below:

LoginComponent.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm!: FormGroup;
isSubmitted=false;
results: any = false;
  constructor(private formbuilder:FormBuilder, private authService: AuthService,
    private router: Router) { }

  ngOnInit() {
    this.loginForm = this.formbuilder.group({
      // email:['', [Validators.required, Validators.email]],
      name: ['',Validators.required],
      password: ['',Validators.required]
    });
    //loginForm.controls.email
    //use getter property instead
    //fc.email
  }
get fc(){
  return this.loginForm.controls;
}
submit(){
  this.isSubmitted = true;
  if(this.loginForm.valid)
  
  this.authService.authUser(this.loginForm.value.name, 
    this.loginForm.value.password).subscribe(data => { 
      //error lies in line above(underlined subscribe)
    this.results = data;
    if (this.results[0].auth) 
    {
    this.authService.setSecureToken(this.loginForm.value.name);
    this.router.navigateByUrl('/user');
    } else{
     console.log("Wrong username or password")
     }
    });
     }
     }

AuthUser function:

 authUser(username: string, pw: string) {
    return this.http.post<any[]>(this.authuser, {
      'username': username,
      'password': pw
    }),
    console.log('user registered!')
  }

Answer №1

Make sure to return an Observable instead of void as pointed out by @Zerotwelve.

To check the data type returned by authUser(), you can use typeof(authUser()).

If you need to return an observable, avoid using subscribe in the authUser() function. Instead, consider using rxjs pipe and map.

Here is an example:

authUser(usernameEmail: string, password: string): Observable<any> {
  return this.http.post<any>('auth', { usernameEmail, password }).pipe(
    map((res) => {
      this.usernameMessage = res.message;
      return res.valid;
    })
  )
}

Answer №2

You need to update the code for authUser() in authService as it currently returns void instead of an Observable. To fix this, ensure that authUser() returns an observable without the need for subscribe().

------ EDIT ------

It appears you are mistakenly passing authUser as a parameter to itself, which might result in unwanted recursion. Instead, make sure to provide the URL of the backend (as a string).

 authUser(username: string, pw: string):Observable<any> {
    return this.http.post(YOUR_URL_HERE, {
      'username': username,
      'password': pw
    });
    console.log('user registered!'); // This line will not be executed due to the preceding "return"
  }

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

Combining default and named exports in Rollup configuration

Currently, I am in the process of developing a Bluetooth library for Node.js which will be utilizing TypeScript and Rollup. My goal is to allow users to import components from my library in various ways. import Sblendid from "@sblendid/sblendid"; import S ...

Creating a unique ngrx operator from scratch that modifies the source observable and outputs its type

I developed a custom operator called waitFor that is being used in my effects like this: public effect$: Observable<Action> = createEffect(() => { return this.actions$.pipe( ofType(myAction), waitFor<ReturnType<typeof myActio ...

Having difficulties incorporating a selected custom repository into a module

Issue with Dependency Injection in NestJS Currently, I am working on implementing SOLID principles in my NestJS project by decoupling my service layer from TypeOrm. One of the benefits of this approach is the ability to switch between using an InMemoryRep ...

Attempting to determine the size of a property within a nested object that exists within an array of objects

I am currently working on implementing a scoring system for two teams. The scoring data is stored in an array that identifies the team (home or away) that scored the goal. My goal is to calculate the total number of goals scored by either team with an ID o ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Tips for generating a new page using Angular 2

I recently set up a fantastic admin project using Angular 2. Check out the demo of the project here. I'm facing an issue while trying to create a new page within this project! You can see exactly what I'm trying to accomplish here. The error I& ...

The RouterLink functionality may not work properly within a nav-bar that combines Bootstrap and Angular frameworks

I have a navigation bar that I want to modify for scrolling behavior based on the type of link. For href links with the "#" symbol, I want the navigation bar to scroll down. However, for routerLink links, I want the page to navigate to the specified route ...

What is the best way to refresh a Load on Demand feature in Nativescript?

In my RadListView, the data displayed changes depending on the day selected by the user in a calendar. Currently, I am using loadOnDemandMode = "Manual" and it functions smoothly until all the available data is loaded. At that point, I trigger listView.no ...

Angular 4: Decoding the json_callback response from the server

When using Angular 4, I made a GET request to the following URL: Here is the code I used: this.http.get('https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK', { params: { format: 'json', tagmode: & ...

The installation of Node on Ubuntu 18.04 encountered an error

Could someone assist me with this problem? I initially had node installed, then uninstalled it using the rm -rf command following online suggestions. Now I am trying to reinstall it using nvm install node However, I'm encountering the following error ...

Deep copying with Object.assign can lead to unexpected issues

I am currently working with an object array that needs to be transformed before it is sent to the controller. Here is the Angular code snippet I am using: sourceObjArray: SourceObject[] = [..]; targetObjArray: SourceObject[]= []; targetObjArray = object. ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...

What is the method of linking interdependent subscriptions that rely on multiple preceding observables?

Just starting out with rxjs, trying to figure out the best way to chain some observables and subscriptions. Here's a simple pseudocode I came up with to demonstrate what I'm attempting to achieve. class Baker implements OnInit { //functions, ...

Submitting an array of objects via HTTP PUT

Struggling to find a way to update a list of Objects on MongoDB in one method call within the Submit button. Spent all day yesterday attempting, but it seems to be unsuccessful. The goal is to update all product sells in the database by entering values for ...

Persuade TypeScript to trust that all necessary keys will be present in an object

I find myself in this particular scenario: const user: UserObj = User.get(userId); if ([user.foo, user.bar, user.baz].some((k) => !k)) throw new Error(`Missing fields for user ${userId}`); const createParams: CreateParams = { firstName: user.first ...

Strategies for sorting through numerous characteristics of a hierarchical array that may stretch across multiple levels of the tree

In order to simplify the process, I am looking for a way to filter multiple properties of a parent-child array that may have multiple levels. This is specifically for an Open Source datagrid library that is utilized by hundreds of users. The array consist ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

Encountering an issue with npm packages failing to install due to an

There seems to be an issue with npm. Kindly report this error at: Error code: EINVALIDTYPE Error type: Typeerror Argument #5: Expected object but received string Error occurred in: inflatableChild (C:\Program Files\nodejs\node_mod ...

TypeScript enables the use of optional arguments through method overloading

Within my class, I have defined a method like so: lock(key: string, opts: any, cb?: LMClientLockCallBack): void; When a user calls it with all arguments: lock('foo', null, (err,val) => { }); The typings are correct. However, if they skip ...

An Angular application caught in an endless cycle of redirects

Currently, I am working on an Angular project that involves the following routing configuration: const routes: Routes = [ { path: '', component: LoginLayoutComponent, children: [ { path: '', redi ...