【问题标题】:When not using a function call, how do I use rxjs timeout?不使用函数调用时,如何使用 rxjs 超时?
【发布时间】:2019-10-21 21:26:41
【问题描述】:

考虑到我当前的代码设置方式,我遇到了一个问题,即一旦加载页面,超时就会立即开始。我遇到的大多数超时示例都出现在函数调用的一部分中,因此这很可能是它们实际开始超时时触发的原因。

为了清楚起见,我的意思是他们可能有

functionName() {
 return this.http.get(this.url).
  pipe(
  timeout(5000)
 )
}

正如您在下面的代码中看到的,我的 observable 是在创建时立即设置的。我已尝试按照文档中的说明使用超时,但似乎正在使用该函数方法。

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private http: HttpClient) { }

  private baseAPIURL: string = environment.baseAPIUrl;
  private apiUrl = `${this.baseAPIURL}/Product/GetProduct`;

  private searchSubject = new BehaviorSubject<ProductSearch>(null);

  searchSelectedAction$ = this.searchSubject.asObservable();

    productOutput$ = this.searchSelectedAction$
    .pipe(
      skip(1),
      switchMap(searchCriteria =>
        this.http.get<ProductResults>(`${this.apiUrl}/${searchCriteria.key1}/${searchCriteria.key2}`, { observe: 'response' })),
      timeout(5000),
      map(response => [response.body]),
      tap(data => console.log(data))
    );

  getProductResults(searchCriteria: ProductSearch): void {
    this.searchSubject.next(searchCriteria);
  }
}

预期的结果是在 5 秒后取消 http 请求,并显示请求已被取消的错误。

现在的实际结果是,一旦页面加载,超时立即开始,甚至没有进行搜索。

我正在使用 RxJS 6。我的 html 只是设置为使用异步管道订阅 productOutput$。

【问题讨论】:

    标签: angular http rxjs timeout


    【解决方案1】:

    如果我没有误解您的问题,可以通过以下任一方式解决:

    1. 使用Subject 而不是BehaviourSubject,或者..
    2. 在 HTTP 调用之前使用 filter(x=&gt; x !== null)。这将确保过滤器之后的任何运算符都不会被调用。随时根据您的需要更新filter 运算符

    【讨论】:

    • 这两种方法似乎都不起作用。我完全理解为什么您建议使用主题而不是行为主题,因为当我想到它时它是有道理的。我也尝试了过滤方法,但似乎也不起作用。
    • 事实证明,答案是通过管道传输 http 响应并将超时时间放在那里。谢谢!
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多