[SOLVED] How to fix error – Property ‘subscribe’ does not exist on type ‘void’?

Question

This Content is from Stack Overflow. Question asked by codelala

I am facing this error, while creating a login form in the word subscribe under the submit function in the code below. The error says Property ‘subscribe’ does not exist on type ‘void’. How can I go about fixing this issue?
The code is as shown:

login component.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")
     }
    });
     }
     }

Solution

You forgot to return in your get(). Also don’t encapsulate the body of lambda functions without returning something. An implicit return is happening if you just do response => response.json(). Otherwise you have to write it like this: response => { return response.json(); }.

Here is an improved version of your method:

get() {
   // return this.mediaItems;
   return this.http.get("/api/MediaItem").map(response => response.json());
}

Also just leave out the this.http = http; in your constructor. Writing public or private in front of the constructor argument already adds it as a class member.

Answered by rinukkusu


This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 4.0.

people found this article helpful. What about you?