Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.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
Angular 角度数据服务被调用两次_Angular - Fatal编程技术网

Angular 角度数据服务被调用两次

Angular 角度数据服务被调用两次,angular,Angular,我有一个angular 7应用程序,在调用服务两次时遇到问题 我有多个观测值连接到一个websocket。在套接字中,我正在侦听不同事件的发生并执行适当的操作 app.module.ts import { DataService } from './data.service'; .... providers: [ DataService ], 一个组件 import { DataService } from './data.service'; .... constructor(privat

我有一个angular 7应用程序,在调用服务两次时遇到问题

我有多个观测值连接到一个websocket。在套接字中,我正在侦听不同事件的发生并执行适当的操作

app.module.ts

import { DataService } from './data.service';
....
providers: [
  DataService
],
一个组件

import { DataService } from './data.service';
....
constructor(private data: DataService) { }
....
ngOnInit() {
  this.data.receiveMessage().subscribe(msg => {
    this.msg = msg;
  });
}
import { DataService } from './data.service';
....
constructor(private router: Router, private data: DataService) { }
ngOnInit() { }
....
两个组件

import { DataService } from './data.service';
....
constructor(private data: DataService) { }
....
ngOnInit() {
  this.data.receiveMessage().subscribe(msg => {
    this.msg = msg;
  });
}
import { DataService } from './data.service';
....
constructor(private router: Router, private data: DataService) { }
ngOnInit() { }
....
data.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import * as io from 'socket.io-client';

@Injectable()
export class DataService {
    receiveMessage() {
      return new Observable(observer => {
        this.socket.on('sendMessage', msg => {
          observer.next(msg);
        });
      });
    }
    ....
    other observables
 }
如果我使用用户可注入提供程序根,同样的事情也会发生


我在应用程序中使用了其他观察值,但我在OnInit中使用的只是这一种方法,但将其取出会导致应用程序停止工作。

添加到app.component.html中,导致整个应用程序渲染两次

添加到app.component.html中,导致整个应用程序渲染两次

您可以使用
rxJS shareReplay
。检查这个谢谢你的建议。事实证明,我在app.component.html中添加了导致整个应用程序渲染两次的内容。愚蠢的错误。您可以使用
rxJS shareReplay
。检查这个谢谢你的建议。事实证明,我在app.component.html中添加了导致整个应用程序渲染两次的内容。愚蠢的错误。