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,组件将接收到更新的数据并进行相应的操作。

相关内容

热门资讯

第6分钟了解(德州ai)外挂智... 第6分钟了解(德州ai)外挂智能ai辅助代打(透视)攻略教程(2023已更新)(哔哩哔哩);相信小伙...
第2分钟了解(tritonpo... 第2分钟了解(tritonpoker)外挂辅助插件安装代打(透视)黑科技教程(2024已更新)(哔哩...
第9分钟了解(WPK技巧)黑科... 第9分钟了解(WPK技巧)黑科技透明挂辅助软件(透视)教你攻略(2024已更新)(哔哩哔哩)是一款可...
七分钟了解(aapoker德州... 七分钟了解(aapoker德州俱乐部)软件透明挂辅助科技(透视)线上教程(2022已更新)(哔哩哔哩...
1分钟了解(Wepoke开发)... 1分钟了解(Wepoke开发)黑科技透明挂辅助黑科技(透视)扑克教程(2021已更新)(哔哩哔哩);...
第六分钟了解(wpk德州ai机... 第六分钟了解(wpk德州ai机器人)外挂辅助插件安装科技(透视)规律教程(2024已更新)(哔哩哔哩...
第1分钟了解(Wepoke技术... 第1分钟了解(Wepoke技术)外挂透明挂辅助下载(透视)实用技巧(2023已更新)(哔哩哔哩);1...
第十分钟了解(新版Wepoke... 第十分钟了解(新版Wepoke)软件透明挂辅助app(透视)曝光教程(2020已更新)(哔哩哔哩);...
第3分钟了解(wepOke)外... 第3分钟了解(wepOke)外挂辅助插件安装app(透视)第三方教程(2021已更新)(哔哩哔哩),...
八分钟了解(德扑之星设置)外挂... 八分钟了解(德扑之星设置)外挂辅助插件安装黑科技(透视)AI教程(2021已更新)(哔哩哔哩);人气...