Angular error in binding value. Element implicitly has an 'any' type. Property 'title' does not exist on type 'Object'.ts(7053)

Viewed 170

I am trying to get the data from api call using Angular and bind it to an variable.

The AppComponent code is as follow.

export class AppComponent {
  title = 'Conveyor';
  clr = 'green';
  serialPortName = "COM123"
  constructor(private convServer:ConvServerService)
  {
    

  }

  ngOnInit() {
    this.convServer.getPortName().subscribe((data)=>
    {

      console.warn(data);
      this.serialPortName = data['title'];
    })
  }
}

The api call is from here. It has following json format data.

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

The service code is as follow:

import { Injectable } from '@angular/core';

import { getLocaleDateFormat } from '@angular/common';
import {HttpClient} from '@angular/common/http'
@Injectable({
  providedIn: 'root'
})
export class ConvServerService {

  constructor(private http:HttpClient) {
    
   }

   getPortName() {
   let url= "https://jsonplaceholder.typicode.com/todos/1";  
   return this.http.get(url);
  }
}

The data is shown properly in web console as shown in the following image. console of web

The data is shown properly in web console but when I want to get specific data like data['title'] it is giving error

Element implicitly has an 'any' type because expression of type '"title"' can't be used to index type 'Object'. Property 'title' does not exist on type 'Object'.ts(7053)

How can I solve it? I am new to angular and web development also. Any suggestion?

2 Answers

try this:

this.serialPortName = data.title;

I guess you recive an object, not an array of objects

The answer to this is that I changed the type of data to any by using data:any and this.serialPortName = data.title;

The changed ngOnInit() function of class AppComponent is here

ngOnInit() {
    this.convServer.getPortName().subscribe((data:any)=>
    {

      console.warn(data);
      this.serialPortName = data.title;
    })
  }

Its working perfect now

Related