将数据从服务发送到可观察的 Get 请求 [英] Send data from service to observable Get request
问题描述
我是 Angular 和 Observables 的新手.我有一个服务,它接收一个 URL,我想在每次使用 NgFor 将新 URL 传递给它时传递给我的 observable 并呈现数据.任何例子都会有所帮助.请帮助似乎没有任何效果.提前致谢
I am new to Angular and Observables. I have a service that receives a URL I want to pass to my observable and render data every time a new URL is passed to it with NgFor. Any example would help. Please help nothing seems to work. Thanks in advance
服务文件
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Event } from '../event/event.interface';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ClientService {
eventUrl ;
constructor(private http: HttpClient) {
}
receiveEvent(eventId){
this.eventUrl = eventId;
console.log(this.eventUrl)
}
renderEvent(eventUrl): Observable<Event[]>{
return this.http
.get<Event[]>(eventUrl)
}
接收组件文件
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ClientService } from '../service/clientService';
import { HttpParams, HttpClient } from '@angular/common/http';
@Component({
selector: 'hero-review',
templateUrl: './review.component.html',
styleUrls: ['./review.component.css']
})
export class ReviewComponent implements OnInit {
public events = [];
constructor(private _clientService: ClientService) {
}
ngOnInit() {
this._clientService.renderEvent('Need to be dynamic URL').subscribe(data => this.events = data);
}
}
发送组件文件
sendEvent(eventId){
let reqUrl = "myEndpoint" + eventId;
this._clientService.receiveEvent(reqUrl);
}
推荐答案
我想我理解你的问题.
http.get(url) 是一个一次性的 observable.它不是可以像主题那样多次触发的流.您需要创建自己的主题并将其用作代理.
The http.get(url) is a single-use observable. It's not a stream that can be triggered multiple times like subjects can. You will need to create your own subject and use that as a proxy.
export class ClientService {
constructor(private http: HttpClient) {
}
private eventPublisher: Subject<Event[]> = new Subject<Event[]>();
receiveEvent(eventId){
// call http client here, and publish results to event publisher
const eventUrl = eventId;
this.http.get<Event[]>(eventUrl).subscribe(response => {
this.eventPublisher.next(response);
});
}
renderEvent(eventUrl): Observable<Event[]>{
// do not subscribe to http client here, subscribe to event publisher
return this.eventPublisher.asObservable();
}
这是发布-订阅设计模式(发布者-订阅者).使用 Angular 阅读此设计模式的其他解决方案可能会很有用,因为这是一个相当简单的例子.
This is the pub-sub design pattern (publisher - subscriber). It might be useful to read up on other solutions to this design pattern using Angular, as this is a fairly trivial example.
您还需要在完成订阅后取消订阅组件以避免内存泄漏.
You will also want to unsubscribe in your component once you're done with the subscription to avoid memory leaks.
这样的东西是一个简单的模式:
Something like this is a simple pattern:
export class MyComponent implements OnInit, OnDestroy() {
constructor(private myService: MyService) { }
private destroyed: Subject<void> = new Subject<void>();
ngOnInit(): void {
this.myService.myMethod().pipe(
takeUntil(() => this.destroyed)
).subscribe(() => {
// do stuff
});
}
ngOnDestroy(): void {
this.destroyed.next(undefined);
this.destroyed.complete();
}
}
虽然如果你需要开始做很多事情,它确实会重复.我个人使用这种方法:https://stackoverflow.com/a/45709120/5367916
Although it does get repetitive if you need to start doing it a lot. I personally use this method: https://stackoverflow.com/a/45709120/5367916
这篇关于将数据从服务发送到可观察的 Get 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!