Connect an Observable to the template with async binding

I've been attempting to link an Observable to a template variable in Angular using the following code:

[class.active]="isBookmarked$ | async"

During the ngOnInit function, I initialize the Observable:

var promise = this.cacheService.getItem(this.bookmarkId).then(() => {
    return true;
}).then(() => {
    return false;
});
this.isBookmarked$ = Observable.fromPromise(promise);

Everything works as expected upon loading the page. However, when I add or remove an item, the template fails to detect the changes.

this.cacheService.removeItem(this.bookmarkId).then(() => { });
// or
this.cacheService.saveItem(this.bookmarkId, true, "bookmarks").then(() => { });

I have experimented with various Observables and even attempted using a Promise without converting it to an Observable, but unfortunately, I haven't been able to resolve the issue.

Answer №1

Considering promises are triggered only once, any subsequent notifications won't be received. To address this, one approach would involve encapsulating cacheService within a new service (if altering the original isn't feasible) in the following manner:

import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/filter";
import "rxjs/add/operator/map";
import { Injectable } from '@angular/core';

interface CacheService {
    getItem(key: any): Promise<any>;
    setItem(key: any, value: any): Promise<any>;
}

interface Item {
    key: any;
    value: any;
}

@Injectable()
export class ObservableCacheService {
    protected readonly items$ = new Subject<Item>();

    constructor(protected readonly cacheService: CacheService) {}

    getItem(key: any) {
        this.cacheService
            .getItem(key)
            .then(value => items$.next({ key: key, value: value }));
        return items$
            .filter(item => item.key === key)
            .map(item => item.value);
    }

    setItem(key: any, value: any) {
        this.cacheService
            .setItem(key, value)
            .then(() => items$.next({ key: key, value: value }));
    }
}

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

Utilize Typescript to Invoke Functions of Different Components in Angular 2

Hello everyone, I am a newcomer to Angular 2 and I'm looking to utilize the value of one component in another component. This will help me populate data based on that particular value. In my setup, I have three Components - App.Component, Category.Co ...

Leveraging the power of Angular 5 to seamlessly integrate two distinct components on

I am exploring a way to render an additional component on the current page instead of navigating to a new one. Here is my setup: <button mat-button color="primary" [routerLink]="['/tripspath', trip.tripId]" style="cursor: pointer">View Rou ...

Having trouble with importing rxjs operators

After updating the imports for rxjs operators in my project to follow the new recommended syntax, I encountered an issue with the "do" operator. While switchMap and debounceTime were updated successfully like this: import { switchMap, debounceTime } ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

"Learn how to programmatically close all panels in an ngb-accordion component in Angular 2 Release 6, leaving only

I have recently begun working on an accordion and I am trying to figure out how to make the first panel expand while keeping the others closed. I attempted to use [closeOthers]="true" but it doesn't seem to be effective. Here is my HTML code: <di ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Ways to show a div when a dropdown option is selected

Currently, I am in the process of designing a form that includes a dropdown menu. Once the user selects a particular option from the list, such as: Software developer a new section will be displayed, showing two additional options: App Developer ...

Implementing Bootstrap 5 JS within an Angular 11 component TypeScript

I am currently working on a project that utilizes Angular 11 and we are aiming to integrate Bootstrap 5 native JS without relying on third-party libraries like ng-bootstrap, MDB, or ngx-bootstrap (jQuery is not being used as well). I understand that using ...

Troubleshoot: Angular fails to display blog post based on specific ID in web browser

In the process of developing a blog application utilizing the MEAN stack, incorporating Angular in the front-end, Node.js in the back-end, and MongoDB for server-side functionalities. A particular issue arises when attempting to access a specific blog by i ...

Is there a solution for resolving the 'cannot post error' in nodejs?

Recently started using node.js I am currently working on a nodejs-experss-mongodb project and I am in the process of implementing a subscription feature that has the following specific requirements: Request Method: POST URL: localhost:8080/api/v1/users/: ...

The error occurred in Commands.ts for Cypress, stating that the argument '"login"' cannot be assigned to the parameter of type 'keyof Chainable<any>))`

Attempting to simplify repetitive actions by utilizing commands.ts, such as requesting email and password. However, upon trying to implement this, I encounter an error for the login (Argument of type '"login"' is not assignable to parameter of t ...

Filtering an object based on a particular string

Is there a way to filter an array based on a string value? I want to display only the rows that contain this specific string or any part of it. For example, consider the following object: 0: {CurrentDriverElement: null, FullName: "1043 TU 147", ...

Tips for debugging and stepping into an npm package containing Typescript source code

Okta, an Angular NPM dependency, is not functioning as expected for me. I am in need of diving into its source code while debugging my application to troubleshoot and resolve the issue at hand. How can I achieve this within my Angular 6 app? Despite using ...

Every time a new message is sent or received, I am automatically brought back to the top of the screen on the

I'm currently working on integrating a chat feature into my Angular Firestore and Firebase app. Everything seems to be functioning well, except for one issue - whenever a new message is sent or received, the screen automatically scrolls up and gets st ...

Having trouble getting the Angular2 boilerplate to start with npm?

Just starting out with Angular2 and attempting to set up the environment using the boilerplate code found at https://github.com/mschwarzmueller/angular-2-beta-boilerplate. After successfully installing my dependencies with npm install, I encountered some ...

What is the importance of moving prop types into a type or interface in React components?

Consider the scenario where I have a functional component: const MyText = ({ value }) => ( <div className="my-fancy-text">{value}</div> ); Now, when utilizing Typescript, I face the need to introduce typing. A straightforward ...

Incorporating data from an api call to establish the starting state of a react component

I have been delving into the world of React and TypeScript while working on a fun project - a word guessing game inspired by Hangman. In this game, players have 5 chances to guess the correct word, which is retrieved from an API call. I populate an array w ...

Storing information from a mat-select element in MongoDB database

I have a collection of Players and Teams. I want to assign players to teams. In my HTML, I create a Team form where users can select players to load: <mat-form-field> <mat-select placeholder="Goalkeepers" formControlName="goalkeeper"> & ...

Having difficulty generating the appropriate output for ng-new app

I am facing difficulty in generating the Angular app after running the 'ng new my-app' command. Here are the outputs I receive upon running the command - 1 Executing 'ng new-mean' app 2 After choosing VS Code and clicking OK - I see ...