Angular Observable错误处理

时间:2017-07-30 09:43:38

标签: angular rxjs

我正在关注Angular教程来构建一个简单的应用程序。当我在输入框中输入术语时,应用程序会向搜索用户发送ajax。我在这里与Observable混淆了。

(1)如果搜索字词短于3个字,我想清除数据。我使用Observable.of返回一个空数组。

(2)如果发生http错误,还会在catch块中返回一个空数组。

然而,在这两种情况中的一种情况之后,似乎流'停止',因为我将this.users指向新的Observable。我应该再做this.users = new Subject()之类的事吗?在这里做正确的方法是什么?

HTML:

<div class="wrapper">
    <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
    <div class="loader" [hidden]="!loading"></div>
</div>

getUserService:

//Sending ajax, return an Observable

成分:

export class searchComponent implements OnInit {

  constructor(private getUserService: GetUserService) { }

    private searchTerms = new Subject<string>();

    users: Observable<User[]>;
    loading: boolean = false;

    search(term: string): void {
        if(term.length >= 3) {
            this.loading = true;
            this.searchTerms.next(term);
        } else {

            //issue (1) occurs after this

            this.users = Observable.of<User[]>([]);
        }
  }

  ngOnInit(): void {
    this.users = this.searchTerms
      .debounceTime(400)
      .distinctUntilChanged()
      //service will not be called after (1) or (2) occurs
      .switchMap(term => this.getUserService.getUser(term))
            .map(data => {
                this.loading = false;
                return data;
            })
      .catch(error => {

        //issue (2) occurs after this

        this.loading = false;
        return Observable.of<User[]>([]);
      });
  }
}

1 个答案:

答案 0 :(得分:3)

你没有在正确的地方做事。它应该是

from PIL import Image
import numpy as np

book_a = Image.open('booka.png')
book_b = Image.open('bookb.png')

#Which image do you like to compare?
input = book_b  #book_a of book_b

print('*** Numpy array Book A')

book_a_ar = np.asarray(book_a)
print(book_a_ar)

print('*** Numpy array Book B')

book_b_ar = np.asarray(book_b)
print(book_b_ar)

#BOOK C is in use to compare those images

print('*** Numpy array Book C')
book_C_ar = np.asarray(input)
print(book_C_ar)

#compare

if np.all(book_b_ar == book_C_ar):
    print('True')

else:
    print('False')