简体   繁体   English

检查并从响应分配给对象的最佳方法?

[英]Best way to check and assign to object from response?

With my angular2 application, i am getting the response and assigning to object as follows, 使用我的angular2应用程序,我得到响应并按如下方式分配给对象,

 seatingConcession: {
                        parking: data.concession.extras.parking ? data.concession.extras.parking : null,
                        restrictedview: data.concession.extras.restrictedview ? data.concession.extras.restrictedview : null,
                        wheelchair: data.concession.extras.wheelchair ? data.concession.extras.wheelchair : null
                    }

sometimes extras does not have value. 有时,临时演员没有价值。 sometimes restrictedview inside extras does not have value. 有时Extras内部的受限视图没有价值。 what is the best way to check and assign the default value . 检查和分配默认值的最佳方法是什么? Whole code: 整个代码:

 this.eventService.getListingsByEventId(this.eventId).subscribe(listresults => {
            this.bindListing(listresults);
        }, error => this.errorMessage = error);
    }
    bindListing(listres: any[]) {
        let price_table = {};
        let section_table = {};
        listres.forEach((data) => {
            data.ticket.seating.forEach((seat: any) => {
                // tslint:disable-next-line:max-line-length
                this.listings.push({
                    section: seat.section, selling: data.price.selling, amount: data.ticket.amount, type: data.ticket.type, row: seat.row, category: seat.category,
                    seatingConcession: {
                        parking: data.concession.extras ? (data.concession.extras.restrictedview || null) : null,
                        restrictedview: data.concession.extras.restrictedview || null,
                        wheelchair: data.concession.extras.wheelchair  || null
                    },
                    deliveryconcession: {
                        instantdownload: data.delivery.instantdownload || null,
                        readytoship: data.delivery.readytoship  || null,
                        unespecifiedshipment: data.delivery.unspecifiedshipment  || null
                    }
                });
                // this.listings.push({ section: seat.section, selling: data.price.selling, amount: data.ticket.amount, type: data.ticket.type, row: seat.row, category: seat.category});
                // tslint:disable-next-line:curly
                if (!price_table.hasOwnProperty(data.price.selling))
                    price_table[data.price.selling] = [];
                price_table[data.price.selling].push(data);
                // tslint:disable-next-line:curly
                if (!section_table.hasOwnProperty(seat.section))
                    section_table[seat.section] = [];
                section_table[seat.section].push(data);
            });
        });

Service js: 服务js:

 getListingsByEventId(EventID: string): Observable<ListingSeller[]> {
        let apiurl = this.appConfig.getAPIUrl() + '/getListingsByEventId';

        return this.http
            .get(apiurl + queryString)
            .map(this.extractData)
            .catch(this.handleErrors);
    }

You can use the following function to achieve what you want. 您可以使用以下功能来实现所需的功能。

function getSafe(fn) {
    try {
        return fn();
    } catch (e) {
        return null;
    }
}

Then use it like this 然后像这样使用

seatingConcession: {
    parking: getSafe(() => data.concession.extras.parking),
    restrictedview: getSafe(() => data.concession.extras.restrictedview),
    wheelchair: getSafe(() => data.concession.extras.wheelchair),
}

See details . 查看详细信息

Another approach would be to execute data.concession.extras = data.concession.extras || {} 另一种方法是执行data.concession.extras = data.concession.extras || {} data.concession.extras = data.concession.extras || {} before actually creating your object. data.concession.extras = data.concession.extras || {}然后再实际创建对象。

You mentioned, 你提到过

" sometimes extras does not have value. sometimes restrictedview inside extras does not have value " 有时附加内容没有价值。有时附加内容中的受限视图没有价值

so, this condition will help you. 因此,这种情况将为您提供帮助。

data.concession.extras ? (data.concession.extras.restrictedview || data.concession.extras ) : null

Here is an example: 这是一个例子:

The first example has restrictedview and the second example doesn't. 第一个示例具有restrictedview ,第二个示例没有。

 data = {} data.concession = { 'extras' : {} } data.concession.extras = { 'restrictedview' : 'restrictedview value'} data2 = {} data2.concession = { 'extras' : 'extras value' } var output = data.concession.extras ? (data.concession.extras.restrictedview || data.concession.extras ) : null var output2 = data2.concession.extras ? (data2.concession.extras.restrictedview || data2.concession.extras ) : null console.log(output) console.log(output2) 

PLEASE RUN THE ABOVE SNIPPET 请运行上面的片段

Observables do try...catch , so for data structures it is possible to follow the pattern: 可观察对象可以try...catch ,因此对于数据结构,可以遵循以下模式:

data$
.map(data => data.complex.path || null)
.catch(() => Observable.of(null))

But for nested structures this will result in complex observable hierarchy which is hard to comprehend. 但是对于嵌套结构,这将导致难以理解的复杂可观察层次结构。

So basically it is possible to treat complex paths to values with this recipe: 因此,基本上可以使用此配方处理通往值的复杂路径:

parking: ((data.concession || {}).extras || {}).parking  || null

This case is conveniently treated by Lodash/Underscore get or a similar helper function: Lodash / Underscore get或类似的辅助函数可以方便地处理这种情况:

parking: _.get(data, 'concession.extras.parking', null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM