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

Utilizing a TypeScript function to trigger an action from within a Chart.js option callback

Currently, I am utilizing a wrapper for Chart.js that enables an animation callback to signify when the chart has finished drawing. The chart options in my code are set up like this: public chartOptions: any = { animation: { duration: 2000, ...

Can an interface be designed to have the option of containing either one property or another?

I am in need of an interface that resembles the following structure: interface EitherOr { first: string; second: number; } However, I want to make sure that this interface can only have either the property first or second. Do you think achieving this ...

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

How can you transform an object literal AST from a TypeScript file into executable code?

Is there a way to convert a JSON or Object Literal file into executable code? const astInJson = {"pos":0,"end":79,"flags":0,"kind":268,"text":"export interface Order {\n\torderId: string;\n\titineraries(id: string): string;\n}&b ...

Encountering an issue with creating an App Runner on AWS CDK

Attempting to deploy my application using App Runner within AWS via CDK. Utilizing the reference from https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apprunner.Service.html. Upon deployment, encountering the following error: create_failed: R ...

Invoke the method saved as a class attribute

Within my codebase, there exists a class named Process. This class has a constructor that takes in a type of object () => void. Initially, everything seemed to be working perfectly fine when I passed this object into the class. However, issues arose whe ...

I encountered an error while attempting to create an npm package from a forked repository on GitHub

Check out this GitHub repository: https://github.com/jasonhodges/ngx-gist Upon running the package command, I encounter an error: rimraf dist && tsc -p tsconfig-esm.json && rollup -c rollup.config.js dist/ngx-gist.module.js > dist/ngx- ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Implementing rxjs switch between multiple observables

As I work with 2 observables, my goal is to retrieve a value from Observable1, then disregard it and only anticipate a value coming from Observable2. After that, repeat the process by getting a value from Observable1 once more, and so on. I am exploring w ...

Transitioning from one provider to another and encountering the error message "Cannot read property prompt of undefined."

This is an example of an alert service in TypeScript public Alert = { prompt: () => { return new Promise((resolve, reject) => { let prompt = this.alertCtrl.create({ title: 'Enter username', ...

The expected function is being executed, yet none of the inner functions are invoked

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One particular unit test involves opening a modal, changing values in a form, and saving them. Everything goes smoothly until it reaches the promise inside the open() ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

Incorporate a personalized Cypress function for TypeScript implementation

I'm in the process of developing a custom cypress command that will enable me to post a file using formData, as the current cy.request does not yet support formData. For the actual POST operation, I am utilizing request-promise-native. To begin with ...

"Encountering issues with importing Splitpanes while using VueJs and TypeScript combination

My VueJS view was originally written in JavaScript using the component "splitpanes" from npm package. The code was functioning well with the following structure: <template> <div> <Splitpanes :dbl-click-splitter="false" :horizont ...

An issue has occurred: TransformError SyntaxError: Unexpected keyword 'const' was encountered

While practicing programming with React-Native, I encountered a problem that I couldn't figure out how to solve. I attempted to use solutions from various forums, but none of them worked. import { StyleSheet, Text, View, Image } from 'react-nativ ...

Vue + TypeScript prop type issue: "'Foo' is intended as a type, but is being treated as a value in this context."

As a newcomer to TypeScript and the Vue Composition API, I encountered an error that left me puzzled: I have a component that requires an api variable as a prop, which should be of type AxiosInstance: export default defineComponent({ props: { api: A ...

Guide to setting up a one-to-many self relation entry in Prisma

I am facing a challenge with a simple schema model that includes one-to-many self relations. In this scenario, my goal is to create a parent entity along with its children in a single transaction. How can I accomplish this task effectively? data-model Y{ ...

Showing object data in TypeScript HTML when the object property starts with a numeral

Below is the function found in the TypeScript file that retrieves data from an API: .ts file getMachineConfigsByid(id) { this.machinesService.getMachineConfigById(id).subscribe((res) => { if (res.status === 'success') { ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...