Home > Blockchain >  error TS2339: Property 'subscribe' does not exist on type '{}'
error TS2339: Property 'subscribe' does not exist on type '{}'

Time:12-31

error TS2339: Property 'subscribe' does not exist on type '{}'. Service file :

import { HttpClient, HttpHeaders,HttpResponse  } from '@angular/common/http';
import { Person } from './person';
import { Injectable } from '@angular/core';
import { throwError } from 'rxjs';
import 'rxjs/add/operator/map'


import { map } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class ApiService {
    baseURL: string = "http://localhost:3000/api/persons/";

constructor(private http: HttpClient) {
}
 
  
 addPerson(id,name)
    {

      var obj={};
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        let formData:FormData = new FormData();  
        formData.append('id',id);  
        formData.append('name',name);   

        this.http.post(this.baseURL   "addPerson?token",formData).pipe(map(data => {
          alert(data);
          return data;
         
        }));

        return obj;
      }
    }

Component file :

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { Person } from './person';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'httppost';
   people:Person[]=[];
  person = new Person();

formData:any = {};


  
  constructor(private apiService:ApiService) {
    this.formData.ID =""; this.formData.Name= "";
  }
 
  ngOnInit() {

  }
 

  addPerson() {
    this.apiService.addPerson(this.formData.ID,this.formData.Name).subscribe(data => {
        console.log(data)
       
      })      
  }
}

have service file in which i have to call my api to get the api's and when i am going to subscribe the method in the other class where i am calling that service method then its showing the error that the property "subscribe " does not exist on type {}

CodePudding user response:

Your service method should return an Observable to use subscribe, right now it is just returning an object, should be something like

 addPerson(id,name): Observable<Person> {
    return this.httpClient.post<Person>(this.baseURL   "addPerson?token",formData);
  }

CodePudding user response:

First of all, I want to mention that using var is not a good practice anymore, so you should consider refactor everything to use let or const (for more info see here).
Secondly, using Typescript without any types or only any as type are also not good practices because you're losing all beneftis of Typescript.

Let's have a look on your current code:

addPerson(id,name)
  {
    var obj={};
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let formData:FormData = new FormData();  
    formData.append('id',id);  
    formData.append('name',name);   

    this.http.post(this.baseURL   "addPerson?token",formData).pipe(map(data => {
      alert(data);
      return data;
    }));

    return obj;
  }

Your function declaration does not contain any types, based on the names I assume they are of type string. The id could be of type number as well.
The return value of your function is Object because you're returning your obj and not the expected Observable because of that you're getting the eror Property 'subscribe' does not exist on type '{}'. (for more info see here).

To make your code you need to adjust your code as following:

// I've added typings but they're not necessary to make it work
addPerson(id: string | number, name: string): Observable<Person> {

    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    const formData: FormData = new FormData();  
    formData.append('id', id);  
    formData.append('name', name);   
    
    // Return here your HTTP request <- This will make it work
    return this.http.post<Person>(this.baseURL   "addPerson?token",formData)
        .pipe(
            map(data => {
                return data;
            })
        );

}

By returning the HTTP request the return value and type of your function is Observable<Person>, so the subscription within your component will work as expected.

Based on your comment, the type for Person could look like this:

export interface Person {
    id: string | number;
    name: string;
}

Since I don't know your data model I cannot be more specific with the interface.

  • Related