3

app.component.ts

import { Component,OnInit } from '@angular/core';
import { DataServiceService } from './data-service.service';
import {IModel} from './imodel';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  resultArray:IModel;
  constructor(private dataService:DataServiceService){}
  ngOnInit(){
    this.dataService.getDataFromURL().subscribe((resultData)=>{
      debugger
      this.resultArray=resultData;
    })
  }
}

dataservice.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataServiceService {

  apiURL='https://jsonplaceholder.typicode.com/posts';
  constructor(private http:HttpClient) { }

  getDataFromURL(){
    return this.http.get(this.apiURL)
  }


}

imodel.ts

export interface IModel {
       userId: number;
        id: number;
        title: string;
        body: string;
}

I have created a Model Interface and trying to fetch data from an API. I have successfully retrieved the data but i am not able to assign the response to resultArray which is an IModel type, which shows are error "Type 'Object' is not assignable to type 'IModel'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'userId' is missing in type 'Object'.

1 Answer 1

13

The http.get method is generic. That means that you can specify the return type like this:

getDataFromURL(): Observable<IModel> {
  return this.http.get<IModel>(this.apiURL)
}

Read more about typescript generics.

Sign up to request clarification or add additional context in comments.

1 Comment

I am not agreed with this answer. it did not assign to value in model .if you try to change or delete one property in the model after you can get the same result. no throw exception. Example delete body: string; after you get data.no throw the exception. it's wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.