可观察的订阅被触发两次

时间:2018-04-07 11:54:37

标签: angular observable subscribe

我对可观察的订阅存在问题。我使用的NotificationService用于从响应任何组件到NotificationComponent的数据传输。现在我需要仅通过一次获得订阅响应,但我两次

以下是我的NotificationService:

export class NotificationSharedService {
    private emitChangeSource = new Subject<any>();
    changeEmitted = this.emitChangeSource.asObservable();

    emitChange(change: any) {
        console.log(change);
        this.emitChangeSource.next(change);
    }

    getData(): Observable<any> {
        return this.changeEmitted;
    }
}

从此处我发送NotificationComponent的当前状态:

const setDefaultImageRequest = this.images.defaultImage(id_image)
    .map((data: ResponseService) => {
        return Image.createFromObject(data.data);
    })
    .subscribe((data) => {
        console.log(data);
        this.defaultImage.id = data.id;
        this.propertyGalleryStatus = true;
        const status = {
            'message': 'Изображение по-умолчанию установлено успешно',
            'status': true
        };
        this.notificationShared.emitChange(status);

    }, (errors) => {
        console.log(errors);
        this.propertyGalleryStatus = true;
    });

    this.subscriptions.push(setDefaultImageRequest);

以下是我订阅的NotificationComponent

constructor(public sharedData: NotificationSharedService) {
    const getSharedData = this.sharedData.getData().subscribe((data) => {
        console.log(data);
        this.status = false;
        this.statusError = false;
        this.state = true;
        if (data.internet_connection !== undefined) {
            if (!data.internet_connection) {
                console.log(data);
                this.message = this.messages.internet_error;
                this.statusError = data.statusError;
                console.log(this.message);

                return;
            }
        }

        this.message = data.message;
        this.status = data.status;
        this.statusError = data.statusError;

        this.fadeNotification = setTimeout(() => {
            this.state = false;
            setTimeout(() => {
                this.status = false;
            }, 5000);
            this.statusError = false;
        }, 4000);
    });

    this.subscriptions.push(getSharedData);
}

以下是响应,其中订阅被触发两次:

enter image description here

以下是通知模板触发两次的屏幕截图

enter image description here

以下是通知模板

<div on-mouseover="hoverNotification()" on-mouseout="unhoverNotification()" [ngClass]="{sbNotificationActive: state, sbNotificationSuccess: status, sbNotificationFailure: statusError}" class="sb-notification">
<div class="sb-notification__wrapper">
    <div class="sb-notification__box">
        <span class="sb-notification__message">{{message}}</span>
        <a *ngIf="!linkStatus" role="button" (click)="reloadPage()" class="sb-notification__reload">Reload page</a>
    </div>
    <div (click)="close()" class="sb-notification__close-button">
        <i class="sb-notification__icon flaticon-cancel"></i>
    </div>
</div>

2 个答案:

答案 0 :(得分:0)

您可以使用简单的标记来防止这种情况。

this.isDataLoaded = false;

// use OnInit instead of constructor
constructor(public sharedData: NotificationSharedService) {                                             
    const getSharedData = this.sharedData.getData().subscribe((data) => {
    console.log(data);
    if(this.isDataLoaded) { this.isDataLoaded = false; return; } 
    if(!this.isDataLoaded) {
      this.isDataLoaded = true;
      // do other stuff
    }
}

答案 1 :(得分:0)

您无法从一个Subscription订阅一个Observable获得多个输出。您的服务是单身人士。在 NotificationService console.log(change); NotificationComponent 中,此console.log(data);多次打印该邮件。从 NotificationService 中删除console.log(),您应该只看到一个输出。

相关问题