[Fixed] How to change the route and make the observable work?

Issue

I am trying to load information from an observable, when I enter the route it loads correctly, but when I change the route with the routerLink the observable stops showing the information with the pipe async.

The way I show the information of the observable is like this:

Profile component

<ng-container *ngIf="this.observable| async as profilevar; else loading">
    <div class="main-content">
        <div class="profile-content shadow">
            <div class="profile-content-top">
                <div class="profile-image">
                    <div class="profile-image-avatar">
                        <img src="{{ profilevar?.profile_url }} "

Here would be the component that contains the elements to change the route:

Navbar component

<div class="nav-bar-mobile">
    <div class="element-bar profile" routerLink="/profile" routerLinkActive="selecteditem">
        <i class="fas fa-user-circle"></i>
    </div>
    <div class="element-bar settigs" routerLink="/settings" routerLinkActive="selecteditem">
        <i class="fas fa-cog"></i>
    </div>
</div>

What works:

  • Load the data by going directly from the browser path

What’s not working:

  • When I change my route using the navbar component and the routerLink

The variable this.observable contains this.db.object(‘/profiles/’ + vid).valueChanges()

How can I solve this problem?

Solution

SOLVED

After investigating I found the solution to my problem!

I managed to solve it by assigning my observable in a Subscription type variable.

    export class ProfileComponent implements OnInit, OnDestroy {

        subscriptionObservable: Subscription;
        observable: Observable<Profile>;
        
        constructor(){
            this.subscriptionObservable = this.observable.subscribe((data: Profile) => 
            {...}));
        }
    
        ngOnDestroy() {
            if (this.subscriptionObservable) {
            this.subscriptionObservable.unsubscribe();
            }
        }
    }

Once I finish with the component I make unsubscribe to the subscriptionObservable variable!

Leave a Reply

(*) Required, Your email will not be published