0
votes

I'm trying to call a service in my angular app but getting the following error on the ngOnInIt function in this line this.currentBlog = this.route.paramMap.pipe(

Type 'Observable' is not assignable to type 'Observable'. Type '{}' is missing the following properties from type 'Blogpost': id, title, short_desc, description, and 3 more.

component.ts file:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, ParamMap} from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { BlogpostService } from '../blogpost.service';
import { Blogpost } from '../../models/blogpost';

@Component({
  selector: 'app-blog-detail',
  templateUrl: './blog-detail.component.html',
  styleUrls: ['./blog-detail.component.css']})
export class BlogDetailComponent implements OnInit, OnDestroy {
  public currentBlog: Observable<Blogpost>;

  constructor(private route: ActivatedRoute,private router: Router,private blogpostService: BlogpostService) {}
  ngOnInit() {
       this.currentBlog = this.route.paramMap.pipe(
                  switchMap((params: ParamMap) =>
                    this.blogpostService.getSingleBlogInformation(+params.get('id'))));
}
  ngOnDestroy(){
    ('blog-detail component destroyed')
  }}

Blogpost.ts:

export class Blogpost {
    id: number;
    title: string;
    short_desc: string;
    description: string;
    author: string;
    image: string;
    created_at: Date;}

Service.ts:

public getSingleBlogInformation(currentBlogId): any {
    let myResponse = this._http.get(this.baseUrl + 'getById.php?id=' + currentBlogId).pipe(
      catchError(this.handleError)
    );
    return myResponse;
  }
2
I'd recommend reading the docs, which show you how to set the generic type. There are also lots of related questions, e.g. stackoverflow.com/q/50492977/3001761. Did you research this at all? - jonrsharpe

2 Answers

0
votes

First, you don't need to create a let in Service.ts to return the result of the HTTP request.

Service.ts:

public getSingleBlogInformation(currentBlogId): Observable<Blogpost> {
    return this._http.get<Blogpost>(this.baseUrl + 'getById.php?id=' + currentBlogId).pipe(
      catchError(this.handleError)
    );
  }

Also, remember that this call return an Observable and in this case: Observable<Blogpost>.

After that, it should work now.

0
votes

You need to type the return value of your service method:

public getSingleBlogInformation(currentBlogId): Observable<Blogpost> {
    return this._http.get<Blogpost>(this.baseUrl + 'getById.php?id=' + currentBlogId).pipe(
      catchError(this.handleError)
    );
  }