成功响应代码未按角度处理

时间:2019-04-25 10:44:45

标签: angular asp.net-web-api

我正在尝试处理asp.net Web API应用程序引发的错误代码。它工作正常,然后记录存在并且抛出错误代码409,但是如果成功则抛出响应代码200则不起作用。如果成功,调试点将永远不会碰到catch块,并且save方法中的结果对象为null,因此不会在if(result)块内部运行。如何显示成功消息。以前,我的asp.net网络api返回IHttpActionResult,并在成功的情况下执行if(结果)块。

Asp.net Web API

[HttpPost]
        [SkipTokenAuthorization]
        [Route("api/classificationoverrides/create")]
        public HttpResponseMessage Create(ClassificationItemViewModelCreate model)
        {
            HttpResponseMessage response;

            var mgrClassificationService = GetService<MGR_STRT_CLASSIFICATION>();

            var isExists = mgrClassificationService.Where(x =>
                x.MANAGERSTRATEGYID == model.ManagerStrategyId && x.PRODUCT_ID == model.ProductId).FirstOrDefault();

            if (isExists == null)
            {
               var mgrClassficationOverride = new MGR_STRT_CLASSIFICATION();
                if (model != null)
                {
                    mgrClassficationOverride.PRODUCT_ID = model.ProductId;
                    mgrClassficationOverride.LEGACY_STRATEGY_ID = model.LegacyStrategyId;
                    mgrClassficationOverride.STRATEGY_ID = model.StrategyId;
                    mgrClassficationOverride.MANAGERSTRATEGY_TYPE_ID = model.ManagerStrategyTypeId;
                    mgrClassficationOverride.MANAGERSTRATEGYID = model.ManagerStrategyId;

                    mgrClassficationOverride = mgrClassificationService.Create(mgrClassficationOverride);
                }
                response = Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                 response = Request.CreateResponse(HttpStatusCode.Conflict, "The item already exists");
            }

            return response;
        }

角度

Save() {

        if (this.ClassificationOverrideDetails.ClassificationEntities.ID === 0) {
            this.Error = '';
            this.classificationOverrideService
                .createClassificationOverrideDetails(this.ClassificationOverrideDetails.ClassificationEntities)
                .then((result) => {
                    if (result) {
                        this.ClassficationOverrideDetailsEvent.next('init');
                        this.notify.success('Classification Overrides Successfully Created');
                    }
                }).catch(err => {
                    if (err.status === 200) {
                        this.notify.error('Classification Overrides Successfully Created');
                    } else if (err.status !== 409) {
                        this.notify.error('An Error Has Occured While Updating Classification Overrides Details');
                    } else if (err.status === 409) {
                        this.notify.error('Product already exists for this Manager Strategy');
                    }
                });
        } 

服务

import { defer as observableDefer } from 'rxjs';
import { refCount, publishReplay } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Response, URLSearchParams, RequestOptionsArgs, Headers, RequestOptions, ResponseContentType } from '@angular/http';
import { AppConfig } from '../app.config';
import { Observable } from 'rxjs/Rx';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Manager360CommonService } from './mgr360.common.service';
import { IClassificationOverride } from '../classification-overrides/classification-override.interface';


@Injectable()
export class ClassificationOverrideService {

        constructor(
                private mgr360CommonService: Manager360CommonService
        ) { }


        getClassificationOverrideDetails(mgrStrategyId: number) {
                return this.mgr360CommonService.httpGet('/api/classificationoverrides/Details/' + mgrStrategyId);
              }

        getClassificationDetails(Id: number) {
                return this.mgr360CommonService.httpGet('/api/classificationoverrides/classificationdetails/' + Id);
              }


        updateClassificationOverrideDetails(classificationOverride: IClassificationOverride) {
                return this.mgr360CommonService.httpPut('/api/classificationoverrides/update', JSON.stringify(classificationOverride));
            }

        createClassificationOverrideDetails(classificationOverride: IClassificationOverride) {
               return this.mgr360CommonService.httpPostAsync('/api/classificationoverrides/create', JSON.stringify(classificationOverride));
            }

        deleteClassificationOverrideDetails(Id: number) {
                return this.mgr360CommonService.httpDelete('/api/classificationoverrides/delete/' + Id);
             }

}

公共服务

   import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { RequestOptions } from '@angular/http';
import { Options } from 'selenium-webdriver/firefox';
import { NotifyService } from '../utilities/notify.service';

const httpPostOptions = {

    headers:
        new HttpHeaders(
            {
                'Content-Type': 'application/json; charset=utf-8',
            }),
    withCredentials: true,
};

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

    webApiLocation = this.getApiLocation();

    private getApiLocation() {
        const port = location.port ? ':56888' : '';
        return location.protocol + '//' + location.hostname + port;
    }

    constructor(private httpClient: HttpClient) { }

     httpGetAsync(url: string) {

            return this.httpClient.get(this.webApiLocation + url, httpPostOptions)
                .pipe(map((response: Response) => {
                    return response;
                }))
                .toPromise()
                .catch((error: any) => {
                    this.onError(error);
                    return Promise.reject(error);
                });
        }
}

1 个答案:

答案 0 :(得分:0)

如果您收到响应状态为catch的响应,则您的应用将不会运行2xx函数中的代码。

如果您想在收到2xx回复时显示消息,则需要放置

this.notify.success('Classification Overrides Successfully Created');

if(result)块之外。

如果要根据成功的状态码(2xx)显示消息,则应发送带有请求选项{observe: 'response'}的请求,然后在then中检查状态码功能

这是第一种情况的代码:

Save() {

        if (this.ClassificationOverrideDetails.ClassificationEntities.ID === 0) {
            this.Error = '';
            this.classificationOverrideService
                .createClassificationOverrideDetails(this.ClassificationOverrideDetails.ClassificationEntities)
                .then((result) => {
                    this.notify.success('Classification Overrides Successfully Created');
                    if (result) {
                        this.ClassficationOverrideDetailsEvent.next('init');

                    }
                }).catch(err => {
                    if (err.status !== 409) {
                        this.notify.error('An Error Has Occured While Updating Classification Overrides Details');
                    } else if (err.status === 409) {
                        this.notify.error('Product already exists for this Manager Strategy');
                    }
                });
        }