Angular 可观察的';s订阅触发两次

Angular 可观察的';s订阅触发两次,angular,observable,subscribe,Angular,Observable,Subscribe,我对observable的订阅有问题。我有一个NotificationService,用于将响应中的任何组件的数据传输到NotificationComponent。现在我只需要订阅一次,但我得到两次 这是我的通知服务: export class NotificationSharedService { private emitChangeSource = new Subject<any>(); changeEmitted = this.emitChangeSource.

我对observable的订阅有问题。我有一个
NotificationService
,用于将响应中的任何组件的数据传输到
NotificationComponent
。现在我只需要订阅一次,但我得到两次

这是我的通知服务:

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;
    }
}
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);
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);
}
这是我订阅的
通知组件:

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;
    }
}
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);
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);
}
这里是订阅触发两次的响应:

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;
    }
}
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);
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);
}

这是两次触发通知模板的屏幕截图:

这是通知模板

<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>

{{message}}
重新加载页面

您可以使用简单标志来防止这种情况

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
    }
}

您不能从订阅一个可观察对象的订阅中获得多个输出。你的服务是单身。在您的通知服务中
控制台.log(更改)和在通知组件中
控制台.log(数据)多次打印该消息。从NotificationService中删除
console.log()
,您应该只看到一个输出。

在屏幕截图上,您可以看到控制台只在第29行触发了两次。我添加了新的屏幕截图,您可以在其中看到两次触发的通知div。您可以展示如何将数据放入模板吗?好像它打印了两次,这意味着有两个订阅是的,当然。我加了一句。你如何显示通知?因为这个模板被渲染了两次,对吗?如何打开它?在NotificationComponent中显示@Component decorator。