繁体   English   中英

Angular 行为主体发射

[英]Angular behaviour subject emiting

我在服务中遇到 BehaviourSubject 问题。 我有服务女巫获取用户位置并通过currentLocation.next({city: 'Some city...'})将其放入currentLocation变量

public currentLocation = new BehaviorSubject({}); //default value is empty object

在我的组件中,我尝试订阅locationService.currentLocation更改并且它正常工作,每个更改都会向我的组件发出一个事件

constructor() {
    this.locationService.currentLocation.subscribe(value => {      
        console.log('CHANGEDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD');
    });
}

但是,如果我尝试订阅另一项服务(例如,根据currentLocation从服务器获取一些数据),订阅仅调用一次且具有undefined的值。 我做错了什么?

请像这样创建一个全球服务。

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class LocationService {
private subject = new Subject<any>();

setLocation(message) {
    this.subject.next(message);
}

clearMessage() {
    this.subject.next();
}

getLocation(): Observable<any> {
    return this.subject.asObservable();
}

}

您可以通过调用 setLocation function 来设置位置,

this.locationService.setLocation(locationObject)

在您需要的任何地方注入位置服务并订阅 getLocation();

this.locationService.getLocation().subscribe(message => { 
 console.log(this.message) });

首先像这样将你的两个服务都注入到 root 中。

定位服务

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class LocationService {
  public currentLocation = new BehaviorSubject({});
}

另一个服务

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
import { LocationService } from "./location.service";

@Injectable({
  providedIn: 'root'
})
export class AnotherService {
  constructor(private locationService: LocationService) {
    locationService.currentLocation.subscribe((val) => console.log('AnotherService: ',val));
  }
}

你的组件应该如下所示。

import { Component, VERSION } from '@angular/core';
import { LocationService } from './location.service';
import { AnotherService } from './another.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private locationService: LocationService, private anotherService: AnotherService) {
    locationService.currentLocation.subscribe((val) => console.log('App Component: ', val));
  }
}

请参阅Stackblitz中的工作示例

如果您看到上面的示例,您将在控制台中找到两个 output。 一个来自组件,另一个来自另一个服务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM