Encase a function with an observable

In my bd service, there is a method called consultaPublicacoes that retrieves all publications from the Firebase database for a specific user email.

bd.service


public consultaPublicacoes(email:string):Observable<any>{

       return this.checkarPublicacoes=new Observable((observer)=>{
           firebase.database().ref(`publicacoes/${btoa(email)}`)
           .orderByKey()
           .once('value')
           .then((snapshot:any)=>{

               let publicacoes:Array<Publicacao>=[] 


               snapshot.forEach((childSnapshot:any) => {
                    let publicacao=childSnapshot.val()
                    publicacao.key=childSnapshot.key
                    publicacoes.push(publicacao)

               });
              return publicacoes.reverse()
           }).then((publicacoes:any)=>{

                publicacoes.forEach((publicacao)=>{
                    firebase.storage().ref().child(`imagens/${publicacao.key}`).getDownloadURL()
                    .then((url:string)=>{
                        publicacao.url_imagem=url

                        firebase.database().ref(`usuario_detalhe/${btoa(email)}`).once('value')
                        .then((snapshot:any)=>{
                            publicacao.nome_usuario=snapshot.val().nome_usuario
                            })

                      })

                 })
                    observer.next(publicacoes)


            })


       })

The PublicacoesComponent has a method called atualizarTimeLine() responsible for assigning the data returned by the Observable to a variable named this.publicacoes.

PublicacoesComponent


export class PublicacoesComponent implements OnInit, OnDestroy {
  public email:string
  public publicacoes:Publicacao[];
  public gostou:boolean=false;

  constructor(private bd:Bd) { }

  ngOnInit() {

    firebase.auth().onAuthStateChanged((user)=>{
      if(user!=null){
      this.email=user.email
      this.atualizarTimeLine()
      }
    })
    this.atualizarTimeLine();

  }

  public atualizarTimeLine(){
    console.log("Updating TimeLine in publicacoes")
    this.bd.consultaPublicacoes(this.email)
    .subscribe((publicacoes:any)=>{

      console.log(publicacoes)
      this.publicacoes=publicacoes

    })

  }
....

MenuComponent


export class MenuComponent implements OnInit {

  email: string;


  constructor(private bd:Bd, private router:Router, private autenticacao:Autenticacao) { }

  ngOnInit() {
    firebase.auth().onAuthStateChanged((user)=>{
      if(user!=null){
      this.email=user.email
      this.atualizarTimeLine()
      }
    })
    this.atualizarTimeLine()
  }


  atualizarTimeLine(){
    console.log("Updating TimeLine From MenuComponent")
    this.bd.consultaPublicacoes(this.email)
    //this.router.navigate(['/home']);
  }

I am looking for a way to update the value of the publicacoes variable in the PublicacoesComponent every time consultaPublicacoes is called from the MenuComponent. Is using an observable in consultaPublicacao the best option for this scenario?

Answer №1

To properly implement the use of 'Subject', follow this example: In your code, create a new Subject instance by using the line firebaseSubject = new Subject(). Then, in your consultaPublicacoes function, call firebaseSubject.next(publicacoes) to pass along the publicacoes data. Within your publicacoesComponent, subscribe to this Subject by writing firebaseSubject.subscribe((publicacoes)=>{}). Finally, in your MenuComponent, make sure to trigger the update of the timeline by calling this.atualizarTimeLine();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The development mode of NextJS is experiencing issues, however, the build and start commands are functioning normally

Just finished creating a brand new Next app (version: 12.0.7) using Typescript and Storybook. Everything seems to be working fine - I can successfully build and start the server. However, when I try to run dev mode and make a request, I encounter the follo ...

The column grid in Angular/Bootstrap RFS is experiencing disruptions

I am currently working with the most recent versions of Bootstrap, Angular, and ngx-Bootstrap. However, I'm facing an issue where Bootstrap's row child classes are being overridden by _rfs.scss (refer to the screenshot). I do not have RFS enabled ...

Troubleshooting Angular: Investigating why a component is failing to redirect to a different route

I am currently implementing a redirect to a new route upon logging in using the following code: this.router.navigate(['/firstPage']); Oddly enough, when my application is initially loaded, this redirection does not occur automatically after logi ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...

Angular's Dynamic Injection: Introducing a new component into its parent component

I am looking for guidance on injecting a component dynamically into another in Angular 4, as well as passing values from the parent component to the child component. If anyone can provide a sample of working code, it would be greatly appreciated. ...

"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click. The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding ...

The issue with session storage persisting even after closing the iframe

Encountering a persistent issue where the sessionStorage remains populated even after closing an iframe and opening another one with the same destination. I assumed that the sessionStorage would be reset and start afresh each time. The iframe is contained ...

Unable to start Angular application, encountering errors while running ng serve

The challenge at hand As I delve into a new project, I've successfully cloned the repository onto my local machine. After utilizing npm install to fetch the necessary packages, running ng serve triggers a series of errors. Despite the application fai ...

Java running on a Tomcat server is failing to serve Angular transpiled files

After configuring my Tomcat server to run through IntelliJ Ultimate Edition, I encountered an issue when trying to load my Angular webpages transpiled into .js files. Even though the files are located within the webapp folder, the server kept giving me a " ...

Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function: fun({ prop1: number, ...

Learn how to easily display Firebase data in a user-friendly HTML table with flexible columns, or seamlessly integrate it into an Angular MAT Table

https://stackblitz.com/edit/dynamic-columns-mat-table This is the current status of my table implementation. The table renders perfectly, but my need is to dynamically set column names without prior knowledge. For instance: Instead of ${element.descript ...

Subscription method in Angular 4 is not triggering the error callback as expected

I successfully handled a bad request for login on the client side, but when attempting to do the same for registration, the error callback is not working as expected. Below are the code snippets: Submit(){ this.userService.create(this.user).subscribe(x=&g ...

adjusting the scrollbar to be positioned at the top when using Material UI stepper component

While using the material ui stepper, I encountered an issue where the scroll bar remains static and hidden behind the step number header when I click on the "save and continue" button. I expect that upon clicking the button, the scroll bar should automatic ...

Custom font for Ionic styling

Greetings! I come to you with a query regarding font usage. Note: I am developing an app for mobile devices (iOS, Android) using Ionic with Angular. I am looking to incorporate the Poppins font into my application. It works perfectly when accessed on a P ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Having trouble with the dropdown button functionality when looping through it in Angular

Currently, I am working with Angular and have implemented a tree-based structure. Within this tree structure, there is a dropdown button labeled "Dropdown." The issue at hand is that when I click on the "Dropdown" button, the dropdown functionality does ...

Vuetify 3 does not display dialogs

I am attempting to integrate vuetify 3.alpha with vue 3. Below are the files I am working with: Temp.vue (obtained from vuetify example) <template> <div class="text-center"> <v-dialog v-model="dialog" w ...

Unable to access the response body of a POST request from an external API within Firebase Cloud Functions

I am encountering an issue with my cloud function in which it makes an http POST request to the LinkedIn API for retrieving an access token. The main problem is that I am unable to retrieve the `body` of the response as it always turns out to be `undefined ...

Angularjs and Angular (5) routing combo

I'm currently exploring the possibility of running angular alongside our existing angularjs application. Instead of immediately diving into the tedious process of transitioning to ngUpgrade, I wanted to attempt running them independently first. My ide ...