Angular的BehaviorSubject无法从http调用中获取数据。
创始人
2024-10-24 01:30:43
0

要在Angular的BehaviorSubject中获取从http调用中获取的数据,可以执行以下步骤:

  1. 创建一个名为data.service.ts的服务文件,并导入所需的Angular模块和操作符:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private dataSubject = new BehaviorSubject(null);
  data$ = this.dataSubject.asObservable();

  constructor(private http: HttpClient) { }
}
  1. 在服务文件中,创建一个方法来执行http调用并将数据发送到BehaviorSubject:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private dataSubject = new BehaviorSubject(null);
  data$ = this.dataSubject.asObservable();

  constructor(private http: HttpClient) { }

  fetchData() {
    this.http.get('your-api-url')
      .subscribe(data => {
        this.dataSubject.next(data);
      });
  }
}
  1. 在组件中注入数据服务,并订阅data$ Observable以获取数据更新:
import { Component, OnInit } from '@angular/core';
import { DataService } from 'data.service';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  data: any;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.data$.subscribe(data => {
      this.data = data;
    });
    this.dataService.fetchData();
  }
}

这样,当组件初始化时,它将订阅data$ Observable,并在数据服务的fetchData方法中执行http调用。一旦数据从http调用中获取并发送到BehaviorSubject,组件将接收到更新的数据并进行相应的操作。

相关内容

热门资讯

每日必看推荐!微乐小程序麻将自... 每日必看推荐!微乐小程序麻将自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)app1、任何微乐...
重要通知!微乐小程序麻将自建房... 重要通知!微乐小程序麻将自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)攻略1、起透看视 微...
最新技巧!微乐自建房辅助工具脚... 最新技巧!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)器小薇(辅助器软件下载)致您一封...
重大通报!微信微乐自建房辅助工... 重大通报!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)工具暗藏猫腻,小编详细说...
分享个大家!微乐自建房辅助工具... 分享个大家!微乐自建房辅助工具免费app,微乐自建房脚本免费入口(开挂自建房)工具1、每一步都需要思...
大神推荐!微乐家乡麻将自建房辅... 大神推荐!微乐家乡麻将自建房辅助app,微乐小程序免费黑科技(开挂自建房)教程所有人都在同一条线上,...
一分钟了解!微信卡五星辅助器,... 一分钟了解!微信卡五星辅助器,微乐家乡麻将自建房辅助app(开挂自建房)app1、很好的工具软件,可...
盘点一款!微乐自建房辅助工具神... 盘点一款!微乐自建房辅助工具神器,微乐自建房脚本免费入口(开挂自建房)教程1、任何微乐自建房辅助工具...
分享实测!微乐自建房辅助工具,... 分享实测!微乐自建房辅助工具,微乐小程序免费黑科技(开挂自建房)软件1、首先打开微乐自建房辅助工具辅...
推荐一款!微乐微信自建房辅助工... 推荐一款!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)插件1、任何微乐微信自建房辅...