首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在.map离子4观测值中跳过迭代

如何在.map离子4观测值中跳过迭代
EN

Stack Overflow用户
提问于 2019-02-22 11:34:50
回答 1查看 107关注 0票数 0

我正在开发一个Ionic 4应用程序,它可以从wordpress中提取帖子。我正在使用mergeMap和forkjoin获取特征图像,以便在主posts页面上获得一个帖子特征图像。

下面的代码在有要获取的特征图像时运行良好,但是如果没有功能图像,那么我就会从throwError中得到一个错误。我似乎无法记录错误。

代码语言:javascript
复制
ERROR Something went wrong ;)

这是我的home.page.ts文件

代码语言:javascript
复制
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LoadingController } from '@ionic/angular';
import { WordpressRestapiService, Post } from '../services/wordpress-restapi.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  categoryId: number;
  private posts : Post[] = [];

  constructor(
    public loadingController: LoadingController, 
    private router: Router,
    private wordpressService: WordpressRestapiService) { }

  async ngOnInit() {
    const loading = await this.loadingController.create();
    await loading.present();

    this.loadPosts().subscribe((posts: Post[]) => {
      this.posts = posts;
      loading.dismiss();
    });
  }

  loadPosts() {
    return this.wordpressService.getRecentPosts(this.categoryId);
  }

  openPost(postId) {
    this.router.navigateByUrl('/post/' + postId);
  }
}

以下是我使用wordpress api的服务文件

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, forkJoin, throwError, empty } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';

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

  baseRestApiUrl: string = 'http://example.com/wp-json/wp/v2/';

  constructor(private httpClient: HttpClient) { }

  getRecentPosts(categoryId: number, page: number = 1): Observable<any[]> {
    // Get posts by a category if a category id is passed
    let category_url = categoryId ? ("&categories=" + categoryId) : "";

    return this.httpClient.get(this.baseRestApiUrl + "posts?page=" + page + category_url).pipe(
      map((res: any) => res),
      mergeMap((posts: any[]) => {
        if (posts.length > 0) {
          return forkJoin(
            posts.map((post: any) => {
              if (post.featured_media === 0) {
                console.log('fired');
                post.media = {};
                return new Post(post);
              }
              else {
                return this.httpClient.get(this.baseRestApiUrl + "media/" + post.featured_media).pipe(
                  map((res: any) => {
                    let media: any = res;
                    post.media =  new Media(media);
                    return new Post(post);
                  }),
                  catchError(error => {
                    return throwError('Something went wrong ;)');
                  })
                );
              }
            })
          );
        }
        return empty();
      }),
      catchError(error => {
        return throwError('Something went wrong ;)');
      })
    );
  }
}

export class Post {
  author: number;
  categories: number[];
  comment_status: string;
  content: object;
  date: string;
  date_gmt: string;
  excerpt: object;
  featured_media: number;
  format: string;
  guid: object;
  id: number;
  link: string;
  media: object;
  meta: object;
  modified: string;
  modified_gmt: string;
  ping_status: string;
  slug: string;
  status: string;
  sticky: boolean;
  tags: number[];
  template: string;
  title: object;
  type: string;
  _links: object;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

export class Media {
  date: string;
  date_gmt: string;
  guid: object;
  id: number;
  link: string;
  modified: string;
  modified_gmt: string;
  slug: string;
  status: string;
  type: string;
  title: object;
  author: number;
  comment_status: string;
  ping_status: string;
  meta: object;
  template: string;
  alt_text: string;
  caption: object;
  description: object;
  media_type: string;
  mime_type: string;
  media_details: object;
  post: number;
  source_url: string;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

我有一个检查,如果post.featured_media === 0然后只是返回post,否则,调用api获取特征图像,但这似乎永远不会返回的帖子。console.log('fired')被调用,但loadingCtrl从未关闭,帖子也从未显示。

如果没有特色图像,但返回所有帖子,我如何才能返回post.media的空对象?

更新:基于David所说的,我用以下内容更新了WordpresRestapiService中的getRecentPosts()函数。这给了我我想要的结果。

代码语言:javascript
复制
getRecentPosts(categoryId: number, page: number = 1): Observable<any> {
// Get posts by a category if a category id is passed
let category_url = categoryId ? ("&categories=" + categoryId) : "";

return this.httpClient.get(this.baseRestApiUrl + "posts?page=" + page + category_url).pipe(
  map((res: any) => res),
  mergeMap((posts: Post[]) => {
    if (posts.length > 0) {
      return forkJoin(
        posts.map((post: Post) => {
          if (post.featured_media === 0) {
            post.media = new Media;
            return of(new Post(post));
          }
          else {
            return this.httpClient.get(this.baseRestApiUrl + "media/" + post.featured_media).pipe(
              map((res: any) => {
                post.media = new Media(res);
                return new Post(post);
              }),
              catchError(val => of(val))
            );
          }
        })
      );
    }
    return empty();
  }),
  catchError(val => of(val))
);

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-22 17:09:42

我认为问题在于,您要在传递到forkJoin的数组中添加一个Post,而不是一个可以观察到的Post。

你可以试试,

代码语言:javascript
复制
import { Observable, forkJoin, throwError, empty, of } from 'rxjs';
...
if (post.featured_media === 0) {
  console.log('fired');
  post.media = {};
  return of(new Post(post));
}

在一个侧面,我会避免像那样使用catchError。它本质上是在吃掉任何javascript错误(以及不成功的HTTP响应)。这就是为什么在这种情况下你没有看到一个有用的错误。

参考资料:(这些不是官方文档,但我发现它们更易读) Stack overflow认为这些链接是代码.

代码语言:javascript
复制
https://www.learnrxjs.io/operators/combination/forkjoin.html
https://www.learnrxjs.io/operators/creation/of.html
https://www.learnrxjs.io/operators/error_handling/catch.html
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54826215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档