Синтаксис rxjs Angular 6/7 - PullRequest
       6

Синтаксис rxjs Angular 6/7

0 голосов
/ 30 октября 2018

Я недавно обновил кодовую базу с Angular 4 на Angular 6. Частью этого было переместить все функции rxjs внутри конвейерных операторов.

Мне интересно, правильно ли я сделал синтаксис, потому что запрос patch, который я делал раньше, больше не работает после обновления синтаксиса.

Вот мой код, который работал в Angular 4:

csrfToken() {
  const url = `path/to/csrf-token`;
  const options = new RequestOptions({
    withCredentials: true,
  });
  return this.http
    .get(url, options)
    .map((res: Response) => {
      return res.text();
    })
    .map((token: string) => {
      if (!token) {
        throw new Error(
          'Successfully requested a CSRF token but the response was empty.'
        );
      }
      return token;
    });
}

writeFavorites(favorites: any[]) {
  const url = `path/to/favorites`;
  // writing favorites requires CSRF Token
  return this.csrfToken().flatMap(token => {
    const opts = new RequestOptions({
      headers: new Headers({
        'MY-TOKEN': token,
        'Content-Type': 'application/json',
      }),
      withCredentials: true,
    });
    return (
      this.http
        .patch(url, JSON.stringify(favorites), opts)
        // PATH currently just replies with 200 and empty body
        .map((res: Response) => {
          return null;
        })
    );
  });
}

Вот код после обновления до Angular 6.

csrfToken(): Observable<string> {
  const url = `path/to/csrf-token`;
  const options = {
    withCredentials: true,
  };
  return this.http.get<string>(url, options).pipe(
    map((res: Response) => {
      return res.text();
    }),
    map((token: string) => {
      if (!token) {
        throw new Error('Successfully requested a CSRF token but the response was empty.');
      }
      return token;
    })
  );
}

writeFavorites(favorites: any[]) {
  const url = `path/to/favorites`;
  // writing favorites requires CSRF Token
  return this.csrfToken().pipe(
    flatMap(token => {
      const opts = {
        headers: new HttpHeaders({
          'MY-TOKEN': token,
          'Content-Type': 'application/json',
        }),
        withCredentials: true,
      };
      return (
        this.http
          .patch(url, JSON.stringify(favorites), opts)
          // PATH currently just replies with 200 and empty body
          .pipe(
            map((res: Response) => {
              // in Angular 7 the typescript compiler 
              // rejects this assignment
              // see comment below
              return null;
            })
          )
      );
    })
  );
}


// Angular 7 - TypeScript compile error: 
// Argument of type 'OperatorFunction<Response, Promise<string>>' 
// is not assignable to parameter of type 'OperatorFunction<string, Promise<string>>'.
// Type 'Response' is not assignable to type 'string'.

Мой вопрос: почему запрос patch не сделан после этого обновления?

Если обновление верное, то, я думаю, проблема в другом месте, но я хотел убедиться, что я тоже новичок в RXJS, так что, возможно, мой синтаксис неправильный.

Спасибо.

1 Ответ

0 голосов
/ 30 октября 2018

если у вас есть синтаксические ошибки в Angular 6 и rxjs V6 +, просто установите rxjs-compat

npm и rxjs-compat

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...