'Property 'subscribe' does not exist on type 'void' in angular-cli
I am new to angular 2 and didn't find any proper answer for similar questions posted.
I am getting Property 'subscribe' does not exist on type 'void' in angular-cli. I tried importing subscribe from rxjs but didn't find that library.
please help solving this issue. please find below my service and component code into which i am calling that service.
// *******************************
// login.service.ts
// *******************************
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/throw';
@Injectable()
export class LoginService {
constructor(private http: Http) { }
getLoginData(){
this.http.get('./json/login.json')
.map((result: Response) => result.json())
.catch(this.getError);
}
private getError(error: Response): Observable<any>{
console.log(error);
return Observable.throw(error.json() || 'Server Issue');
}
}
// *******************************
// login.component.ts
// *******************************
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../login.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [LoginService]
})
export class LoginComponent {
usernameModel: string;
passwordModel: string;
validLogin: Boolean;
constructor(private router: Router, private loginService: LoginService) { }
homeNav(){
if(this.usernameModel === 'jay' && this.passwordModel === 'Jay'){
this.validLogin = true;
this.router.navigate(['/home']);
}
else{
this.validLogin = false;
console.log('Login Error');
}
this.loginService.getLoginData()
.subscribe(
data => console.log(data)
);
}
}
Solution 1:[1]
You should return the http call, and be sure to always add typehinting to have your IDE pick up on these errors beforehand
getLoginData(): Observable<any> {
return this.http.get('./json/login.json')
.map((result: Response) => result.json())
.catch(this.getError);
}
Solution 2:[2]
I'm using Angular 13
[Post.services.ts]
Simple use return on the API
postProduct (data: any) {
return this.http.post<any>(" http://localhost:3000/productList/", data)
}
[Post.component.ts]
addProduct(){
if(this.productForm.valid){
this.API_DailogService.postProduct(this.productForm.value)
.subscribe({
next:()=>{
alert("Product added successfully!")
},
error: () =>{
alert("Error while adding product!")
}
})
}
}
[Post.component.html]
<button (click)="addProduct()">Save
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Poul Kruijt |
| Solution 2 | Chadrack Kyungu |
