要在Angular的BehaviorSubject中获取从http调用中获取的数据,可以执行以下步骤:
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) { }
}
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);
});
}
}
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,组件将接收到更新的数据并进行相应的操作。