订阅的有角度限制发射

时间:2019-12-17 09:42:07

标签: angular typescript rxjs

我正在尝试限制订阅的发出:

我的对象首选项可以随时更改。 API请求仅应在x更改后第一次运行。 我添加了distinctUntilChanged,但API请求仅在初始化时触发,而当我触发changeY或changeX时,没有任何请求运行,并且console.log显示相同的prev.x和current.x值。当我删除distinctUntilChanged时,每当我更改changeX()或changeY()都会触发api请求

test.page.ts:

import {Component, OnDestroy, OnInit} from '@angular/core';
import {AuthService} from '../_auth/auth.service';
import {AppService} from '../_app/app.service';
import {User, UserProfileService} from '../../api';

import {Preferences} from '../_interfaces/preferences';
import { Subject} from 'rxjs';
import {tap, takeUntil, switchMap, take, distinctUntilChanged} from 'rxjs/operators';

@Component({
    selector: 'app-test',
    templateUrl: './test.page.html',
    styleUrls: ['./test.page.scss'],
})
export class TestPage implements OnInit, OnDestroy {


    public menu: any;
    private user: User;
    public preferences: Preferences;
    private readonly destroy$: Subject<void> = new Subject();
    private i = 1;

    constructor(public appService: AppService, public authService: AuthService, public userProfile: UserProfileService) {


        this.authService.currentUser
            .pipe(
                take(1),
                tap((user: User) => this.user = user),
                switchMap(() => this.appService.currentPreferences.pipe(
                    distinctUntilChanged((prev, current) => {
                        console.log(prev.x, current.x)
                        return prev.x === current.x;
                    }),
                    tap((preferences: Preferences) => this.preferences = preferences), takeUntil(this.destroy$))),
// fire Api request
                switchMap(() => this.userProfile.getMenu(this.user.id, this.preferences.x).pipe(take(1), takeUntil(this.destroy$))),
                takeUntil(this.destroy$)
            )
            .subscribe(res => {
                this.menu = res;
                alert('Request API done');

            });


    }
        // used in html on button (click)="changeX()"
    changeX() {
        const copyPreferences: Preferences = this.preferences;
        copyPreferences.x = new Date();
        this.appService.setPreferences(copyPreferences);
    }
             // used in html on button (click)="changeY()"
    changeY() {
        const copyPreferences: Preferences = this.preferences;
        copyPreferences.y = new Date();
        this.appService.setPreferences(copyPreferences);
    }

    ngOnInit() {
    }

    ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
    }


}

preferences.ts:

export interface Preferences {

    appToken?: string;
    shiftId?: number;
    restaurantId?: number;
    restaurants?: any;
    x?: any;
    y?: any;
}

app.service.ts

import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';
import {Observable, ReplaySubject} from 'rxjs';


@Injectable({
    providedIn: 'root'
})
export class AppService {


    public currentPreferences: Observable<any>;
    public prefernecesState = new ReplaySubject<any>(1);

    constructor(private storage: Storage) {


        this.currentPreferences = this.prefernecesState.asObservable();


            this.setPreferencesState();

    }

    async setPreferencesState() {
        this.storage.get('preferences').then(res => {
            if (res) {
                 this.prefernecesState.next(res);
            }
        });
    }


    public setPreferences(preferences) {
        this.storage.remove('preferences');
        this.storage.set('preferences', preferences);
        this.prefernecesState.next(preferences);
    }


}

1 个答案:

答案 0 :(得分:1)

const copyPreferences: Preferences = this.preferences;

实际上并没有创建副本,只是创建了对同一对象的另一个引用。 copyPreferences的任何突变都自动是this.preferences的突变。因此,测试prev.x === current.x将始终返回true,因为prevcurr是同一对象。

浅拷贝就足够了:

const copyPreferences = Object.assign({}, this.preferences);
相关问题