Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rxjs 具有BehaviorSubject的Angular SharedService在刷新时丢失数据_Rxjs_Angular5_Subject_Behaviorsubject_Sharedservices - Fatal编程技术网

Rxjs 具有BehaviorSubject的Angular SharedService在刷新时丢失数据

Rxjs 具有BehaviorSubject的Angular SharedService在刷新时丢失数据,rxjs,angular5,subject,behaviorsubject,sharedservices,Rxjs,Angular5,Subject,Behaviorsubject,Sharedservices,我创建了sharedService,它可以完美地工作,我可以将数据从一个组件共享到另一个组件(这两个组件在不同的模块中都是不相关的组件) 数据传输如下: AdminDashboard.Component(更新值)==>conference.Component(获取新的更新值) 问题:刷新conference.component时,我丢失了值 EventService.ts import { Injectable } from '@angular/core'; import { Observa

我创建了sharedService,它可以完美地工作,我可以将数据从一个组件共享到另一个组件(这两个组件在不同的模块中都是不相关的组件)

  • 数据传输如下:
AdminDashboard.Component(更新值)==>conference.Component(获取新的更新值)

问题:刷新conference.component时,我丢失了值

EventService.ts

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { importExpr } from '@angular/compiler/src/output/output_ast';
import {Events} from '../models/event.model'


@Injectable()
export class EventService {
    private dataSource = new BehaviorSubject(null);
    sendMessage(data) {
        this.dataSource.next(data);
    }

    getMessage(): Observable<any> {
        return this.dataSource.asObservable();
    }
}
conference.component(url/会议) 在这里,我保存消息中的值并绑定到ui

import { Component, OnInit } from '@angular/core';
import { EventService } from'../../shared/sharedServies/eventService.service';
import { Subscription } from 'rxjs/Subscription';

export class ViewconferenceComponent implements OnInit {
    message: any;
    constructor(private EventService: EventService) {
        this.subscription = this.EventService.getMessage().subscribe(message => {
            console.log(message)
            this.message = message;
        });
    }

}
问题:

  • 当我在/conference页面上获取数据时,在刷新 服务保留值丢失,我不明白会发生什么情况

  • 我还需要向sharedService添加json,它将如何实现


这是意料之中的,因为当您“切换”组件时,它们会被销毁。您可以通过向服务中添加状态变量来快速解决此问题

就个人而言,我鼓励你使用一些像ngRx这样的州立图书馆

import { Component, OnInit } from '@angular/core';
import { EventService } from'../../shared/sharedServies/eventService.service';
import { Subscription } from 'rxjs/Subscription';

export class ViewconferenceComponent implements OnInit {
    message: any;
    constructor(private EventService: EventService) {
        this.subscription = this.EventService.getMessage().subscribe(message => {
            console.log(message)
            this.message = message;
        });
    }

}