首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >订阅service in service angular不起作用

订阅service in service angular不起作用
EN

Stack Overflow用户
提问于 2017-06-23 17:53:57
回答 2查看 2.4K关注 0票数 1

我正在使用angular component中的Rxjs observable并学习一些东西。我有一个场景,我需要根据一些事件将数据从一个组件传递到另一个服务。

Price.service.ts

代码语言:javascript
运行
复制
export class PriceService{
   private priceUpdate: BehaviorSubject<Object> = new BehaviorSubject({});
   private oldPriceUpdate: BehaviorSubject<Object> = new BehaviorSubject({});
   getPriceUpdate(){
       return this.priceUpdate.asObservable();
   }
  getOldPrice(){
      return this.oldPriceUpdate.asObservable();
  }
}

以上服务在组件中使用,用于获取价格更新。

Price.component.ts

代码语言:javascript
运行
复制
@Component({
  selector: 'price',
  templateUrl: 'price.component.html',
  styleUrls: ['price.component.css']
})
export class PriceComponent{
    updateIndicator: BehaviorSubject<Object> = new BehaviorSubject({});
  constructor(private priceService:PriceService, private techIndicator:TechnicalIndicatorService){
    this.techIndicator.subscribeUpdateIndicator(this.updateIndicator.asObservable());
    this.priceService.getPriceUpdate().subscribe(
      (newPrice:any) => {
         this.updatePrice(newPrice);
      }
    )
   this.priceService.getOldPriceUpdate().subscribe(
     (oldPrice:any ) => {
        //some business logic
        this.updateIndicator.next({{data: data, ....});
    });
  }
  private updatePrice(newPrice:any){
     //.... some business logic.... 
      this.updateIndicator.next({data: data, ....});
  }
}

在从component中的PriceService获得新价格后,我还有另一个服务,我正在做一些技术研究。我需要将数据传递给服务,为此我使用了component中的behaviour主题,而service订阅了它。(与通常的组件订阅方法不同。)

请让我知道这是否是使用observable的有效方式。

TechnicalIndicator.service.ts

代码语言:javascript
运行
复制
export class TechnicalIndicatorService{
    subscribeUpdateIndicator(updateIndicator:Observable<Object>){
     updateIndicator.subscribe(
         (obj:any) => {
          // some logic
         });
    }
}

但是,订阅在TechnicalIndicatorService中只有效一次。对于之后的任何数据更新,its不会触发订阅。请让我知道我这里遗漏了什么。

EN

回答 2

Stack Overflow用户

发布于 2017-06-25 02:28:07

你的科目太多了。你可以防止它们,让它变得更简单。

从您所写的内容中,我了解到您希望通知TechnicalIndicatorServicepriceUpdateoldPriceUpdate进行一些更改。

解决方案1:

为此,您根本不需要使用component。你可以做到的。直接将PriceService注入TechnicalIndicatorService

TechnicalIndicatorService:

代码语言:javascript
运行
复制
export class TechnicalIndicatorService{
    constructor(private priceService: PriceService){
       priceService.getPriceUpdate().subscribe(this.doSomething);
       priceService.getOldPrice().subscribe(this.doSomething);
    }
    private doSomething(update){
    }
}

你不需要在组件中写任何东西。

解决方案2:

但是你不想让它们知道彼此,而只想从组件中做,那么你可以这样做:

PriceComponent

代码语言:javascript
运行
复制
export class PriceComponent{
   constructor(
       private priceService:PriceService,
       private techIndicator:TechnicalIndicatorService
   ){
       this.techIndicator.subscribeUpdateIndicator(
          return Observable.merge(
             priceService.getPriceUpdate(),
             priceService.getOldPrice()
          );
       );

    }
}

如果你仍然想使用主题,请告诉我,我会检查它们失败的原因。

票数 1
EN

Stack Overflow用户

发布于 2020-12-03 00:17:42

你好,伙伴,你应该在顶层模块中提供它

代码语言:javascript
运行
复制
import { Post } from './../contance/models/posts';
import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { USER, User } from '../contance';
import { usersState } from './states/users.state';
import { deleteFromArray, updateArray } from '../utils/array-utils';

@Injectable({
  providedIn: 'root'
})
export class StoreService {
  state = {
    usersState,
  }
  private Posts = new Subject<Post[]>()
  posts = this.Posts.asObservable()
  constructor() {
  }

  getUser() {
    if (localStorage.getItem(USER)) {
      return JSON.parse(localStorage.getItem(USER)) as User
    }
  }

  public postsActions = {
    fetch: (posts: Post[]) => this.Posts.next(posts),
    delete: (id: number) => deleteFromArray('id', id, this.Posts.observers),
    edit: (object: Post) => updateArray('id', object.id, this.Posts.observers, object, true)
  }
}

您需要在app.module中提供服务:

代码语言:javascript
运行
复制
/**
 * @license
 * Copyright Akveo. All Rights Reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 */
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { CoreModule } from './@core/core.module';
import { ThemeModule } from './@theme/theme.module';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {
  NbChatModule,
  NbDatepickerModule,
  NbDialogModule,
  NbMenuModule,
  NbSidebarModule,
  NbToastrModule,
  NbWindowModule,
} from '@nebular/theme';
import { HttpRequestModule } from './@core/interceptor/http-request.module';
import { StoreService } from './@core/context/store.service';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpRequestModule,
    AppRoutingModule,
    NbSidebarModule.forRoot(),
    NbMenuModule.forRoot(),
    NbDatepickerModule.forRoot(),
    NbDialogModule.forRoot(),
    NbWindowModule.forRoot(),
    NbToastrModule.forRoot(),
    NbChatModule.forRoot({
      messageGoogleMapKey: 'AIzaSyA_wNuCzia92MAmdLRzmqitRGvCF7wCZPY',
    }),
    CoreModule.forRoot(),
    ThemeModule.forRoot(),
  ],
  providers: [StoreService],
  bootstrap: [AppComponent],
})
export class AppModule {
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44718444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档