承诺不会在catchError打字稿中

时间:2019-05-29 14:39:00

标签: typescript promise async-await ionic4 resolve

在catchError中我需要resolve(false),但这不起作用。

在我的loin.page.ts

async login() {
      if (this.signin.valid) {
        const controls = this.signin.controls;
        const valid = await this.authService.signin(controls.email.value, controls.password.value);
        if (valid) {
            this.navCtrl.navigateRoot('/user', { animated: true});
        } else {
            console.log('Bad credentials');
        }
    }
  }

authService.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';

constructor(private http: HttpClient) {}

signin(email, password) {

        const headers = new HttpHeaders({
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        });
        const data = {
            email,
            password
        };
        const url = URL_SERVICIOS + 'xxx';
        return new Promise ((resolve) => {

            this.http.post(url, data).pipe(
                map( (result: any) => {
                    this.credentials = result;
                    resolve(true);
                }),
                catchError(() => {
                    return Promise.resolve(false);
                })
            ).subscribe();
        });
     }

此代码以'return Promise.resolve(false);'结尾,并且不在 loin.page.ts

中继续

2 个答案:

答案 0 :(得分:0)

那是因为您返回的是一个新的Promise,它将解决而不是调用resolve回调。

尝试做:

   var result = count  
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse 
      })
     .Select(chunk => new {
        key = chunk.Key,
        summary = chunk.Aggregate(
          Tuple.Create(0m, new List<Batch>()),
          (s, a) => Tuple.Create(s.Item1 + a.Quantity, 
                                 s.Item2.Concat(a.batchs).ToList())
      })
     .Select(item => new {
        Item = item.key.Item,
        FromWarehouse = item.key.FromWarehouse,
        ToWarehouse = item.key.ToWarehouse,
        Quantity = item.summary.Item1,
        Batches = item.summary.Item2
      }); // Add ToArray() if you want to materialize

答案 1 :(得分:0)

您可以尝试如下所示,在成功和捕获块中都用type注释并使用resolve()

...
 return new Promise<boolean>((resolve) => {
     this.http.post(url, data).pipe(
         map( (result: any) => {
             this.credentials = result;
             resolve(true);
         }),
         catchError(() => {
             resolve(false);
         })
         ).subscribe();
     });
...