1

I've a very basic question related to a service. I've this method getAllArticlesFromDb in my service that will fetch data from an API using HTTP's GET call. Here is the method:

article.service.ts

getAllArticlesFromDb() : Observable<any> {
  return this._httpClient.get('https://obscure-tundra-38074.herokuapp.com/api/articles');
}

I thought I should not use <any> as I know the structure of the Object that is returned by the API. So I created a model:

article-model.ts

export class Article {
    articleid: string | undefined;
    title: string | undefined;
    content: string | undefined;
    date: string | undefined;
    contributor: string | undefined;
}

The problem starts here. Why I can't modify my service method like this:

import { Article } from './model/article-model';

getAllArticlesFromDb() : Observable<Article> {
  // same GET call
}

I'm getting this error:

"Type 'Observable Object' is not assignable to type 'Observable Article'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 'Article': articleid, title, content, date, and 1 more."

Please correct my mistake.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110
  • 1
    Does this answer your question? [Angular 4 - Http to HttpClient - property 'someproperty' does not exist on type Object](https://stackoverflow.com/questions/47202177/angular-4-http-to-httpclient-property-someproperty-does-not-exist-on-type) – R. Richards May 25 '21 at 18:58
  • @R.Richards, Sure I'll have a look. There is an answer below also. I'll check that first. I'll show both the answers to my tech lead. – Tanzeel May 25 '21 at 19:00

2 Answers2

2

You need to use the generic overload on the HttpClient get call. Then the return will match what is specified in your method signature.

import { Article } from './model/article-model';

getAllArticlesFromDb() : Observable<Article> {
  return this._httpClient.get<Article>('https://obscure-tundra-38074.herokuapp.com/api/articles');
}

After reading the end point url and the name of your method you likely meant to return an array of that type in which case change it to Array<Article>>.

import { Article } from './model/article-model';

getAllArticlesFromDb() : Observable<Array<Article>> {
  return this._httpClient.get<Array<Article>>('https://obscure-tundra-38074.herokuapp.com/api/articles');
}
Igor
  • 60,821
  • 10
  • 100
  • 175
1

Because this.http.get returns an Observable<any>. You can specify what object type get returns with this.http.get<Article> or cast it with this.http.get(<parameters>) as Observable<Article>

Dan Percic
  • 51
  • 2
  • 5