4

estoy haciendo un curso de Angular con Firebase de Youtube, y tengo un problema con el Observable, o eso creo, os dejo el link del video que estoy viendo:

https://www.youtube.com/watch?v=Gw-cKmrEog0&list=PL_9MDdjVuFjFPCptPjhr3iuzPK0_Nrm0s&index=9&t=2s

Estoy tratando de recuperar la información del blog a través del ID, para que una vez pulsas, al entrar en dicho post, te saque todo lo que contiene.

Este es mi código del blog.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Route } from '@angular/router';
import { BlogService } from '../blog.service';
import { Observable } from 'rxjs';
import { BlogsInterface } from '../../../models/blogs.interface';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  //blog$: Observable<BlogsInterface | undefined> | undefined;
  public blog$: Observable<BlogsInterface>;
  //blog$ = new Observable<BlogsInterface>();

  constructor(private Route: ActivatedRoute, private BService: BlogService) { }

  ngOnInit() {
    const idBlog = this.Route.snapshot.params.id;
    //this.blog$ = this.BService.getBlogId(idBlog);
  }

}

Y este es el codigo del Blog.service.ts:

import { Injectable } from '@angular/core';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFirestore } from '@angular/fire/firestore';
import { BlogsInterface } from '../../models/blogs.interface';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BlogService {
  
  constructor(private angularFS: AngularFirestore) { }
  
  public getBlogs():Observable<BlogsInterface[]>{
    
    return this.angularFS.collection('blogs').snapshotChanges().pipe(map(actions => actions.map(a => {
      const data = a.payload.doc.data() as BlogsInterface;
      const id = a.payload.doc.id;
      return {id, ... data};
    })))
  }

  public getBlogId(id: BlogsInterface):Observable<BlogsInterface | undefined>{
    const BlogId = this.angularFS.doc<BlogsInterface>(`blogs/${id}`).valueChanges();
    return BlogId;
  }

}

Y este es el error que me da al compilar:

 Error: src/app/components/blogs/blog/blog.component.ts:15:10 - error TS2564: Property 'blog$' has no initializer and is not definitely assigned in the constructor.

15 public blog$: Observable<BlogsInterface>;
src/app/components/blogs/blog/blog.component.ts:22:5 - error TS2322: Type Observable<BlogsInterface | undefined>' is not assignable to type 'Observable<BlogsInterface>'.
      Type 'BlogsInterface | undefined' is not assignable to type 'BlogsInterface'.
        Type 'undefined' is not assignable to type 'BlogsInterface'.

22 this.blog$ = this.BService.getBlogId(idBlog);

Como veis he probado dos formas, que están comentadas, que he visto en la documentación de Angular, pero no entiendo si es así o no.

No sé si lo estoy preguntando bien, si no eliminarlo, pero no he encontrado ninguna solución, si alguien me puede echar una mano se lo agradecería, ya que llevo dos días atascado y no lo logro. Un saludo.

4
  • 1
    hola Daniel y bienvenido tu pregunta es buena, seria muy útil que pusieras el código del servicio BlogService
    – junior
    el 18 may. 2021 a las 12:04
  • Hola, muchas gracias por tu respuesta, ya he añadido arriba el código, si hace falta algo mas, os lo pongo. Un saludo. el 18 may. 2021 a las 13:38
  • trata cambiando el tipo de observable de blog$ a Observable<BlogsInterface | undefined>
    – junior
    el 18 may. 2021 a las 14:08
  • Probé a poner el undefined, y el error se va, pero siempre me devuelve el ID como undefined, por lo que no me vale, lo que he pensado, es que en el tutorial lo hace con Angular 8, y yo lo estoy haciendo en Angular 11, por lo que igual cambio algo, de la sintaxis, pero no doy con ello. Gracias por tu respuesta. el 18 may. 2021 a las 15:40

1 respuesta 1

0

Ok no se si entendi bien pero creo que puedo ayudarte, primero tal como dices estas usando angular 11 y muy probablemente creaste el procto de angular en modo stricto, por eso tenes el primer error:

Error: src/app/components/blogs/blog/blog.component.ts:15:10 - error TS2564: Property 'blog$' has no initializer and is not definitely assigned in the constructor.

Para arreglar esto tenes que hacer inicializar el objeto y no solo dejarlo con el tipo, de la siguiente manera:

public blog$: Observable<BlogsInterface> = new Observable<BlogsInterface>();

El siguiente error:

src/app/components/blogs/blog/blog.component.ts:22:5 - error TS2322: Type Observable<BlogsInterface | undefined>' is not assignable to type 'Observable<BlogsInterface>'.
  Type 'BlogsInterface | undefined' is not assignable to type 'BlogsInterface'.
    Type 'undefined' is not assignable to type 'BlogsInterface'.

Lo solucionas dejando el tipo de la funcion en el servicio de la siguiente forma

 public getBlogId(id: BlogsInterface):Observable<BlogsInterface>

Intenta esto y me comentas como te fue para poder ayudarte.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.