0

Disclaimer: I'm a beginner in using Vue.js, and being used to Angular I went the Class Component way. I know that not the proper Vue.js way, but this is a fun pet project, so I elected to do it in a unusual way in order to try new things.

I have a simple component, "MyForm", written using Typescript and the Class Component Decorator.
To simulate a service, I made a Typescript class "MyService", that contain methods simulating an API call using an RxJs Observable objects with a delay. The the service function update the data contained in another class "MyDataStore", which is then read by the component to update the view.

But when the observable returns and changes the Data in the Store, it does not update the displayed data (until the next clic on the button).

The component

<template>
    <v-app>
        <pre>
            <v-btn @click="clickBouton()">Load</v-btn>

            Form counter: {{counter}}
            Service counter: {{service.counter}}
            Store counter : {{store.counter}}

            RxJs data : {{store.data}}
        </pre>
    </v-app>
</template>

<script lang="ts">

import { MyDataStore } from '@/services/MyDataStore';
import { MyService } from '@/services/MyService';
import Vue from 'vue'
import Component from 'vue-class-component';

@Component
export default class MyForm extends Vue {

    public counter = 0;

    public store = MyDataStore;
    public service = MyService;

    clickBouton(){
        this.counter++;
        MyService.Increment()
        MyService.getData();
    }
}
</script>

The service

import { of, from, concatMap, delay } from 'rxjs';
import { MyDataStore } from './MyDataStore';

export class MyService {
    public static counter = 0

    // Update the data store with a new value every 10s
    static getData(){
        from(["A", "B", "C", "D"]).pipe(concatMap(item => of(item).pipe(delay(10000)))).subscribe((res: any) => {
            MyDataStore.data = res;
        });
    }

    static Increment(){
        MyDataStore.counter++;
        MyService.counter++
    }
}

The "DataStore"

export class MyDataStore {
     static data: string;
     static counter = 0;
}

Any help or tutorial are welcome.

1 Answer 1

0

Hey In the end you get a observable. You need to subscribe a value of your component to it and descubscribe it if you destroy your component. If you are using Vue 2 you can use async pipes/filter in order to automate this process.

I found this tutorial:

https://medium.com/@p.woltschkow/a-better-practice-to-implement-http-client-in-vue-with-rxjs-c59f93bfa439

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.