Search code examples
angularsubscribe

Proper use of subscribe() to Observable with entity representation


I struggle making a simple Service - Component connection when using my own entity representation as .ts file:

news.ts file:

export interface News {
    id: number,
    something: String
}

Im passing this to service:

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { News } from '../interfaces/news';

@Injectable({
  providedIn: 'root'
})
export class SomeService {
  private newsUrl = '...';

  constructor(private http: HttpClient) { 
  }

  public getNews(): Observable<News> {
    return this.http.get<News>('...');
  }
}

And when I try to pass this to component like this:

export class SomeComponent {
  public news: News[] = [];

  constructor(private newsService: SomeService) {}

  public getNews(): void {
    this.newsService.getNews().subscribe(
      (response: News[]) => { this.newsArray = response }
... error
    )
  } 

I get "No overload matches this call.." Its probably trivial but im newb


Solution

  • Did you check this part:

    public getNews(): Observable<News> {
        return this.http.get<News>('...');
      }

    Here if you are getting Array of News then it may be required to put array of News in the get call as well.

    I hope this works. Thank you