Отображение двух наблюдаемых в один из combineLatest

#angular #typescript #rxjs #observable

#angular #машинописный текст #rxjs #наблюдаемый

Вопрос:

У меня есть два набора данных:

Модель данных: taxControlReference

  [
    {
        "providerId": "HE",
        "taxTables": {
            "STAT": [
                1
            ]
        }
    },
    {
        "providerId": "REMC",
        "taxTables": {
            "STAT": [
                1
            ]
        }
    },
    {
        "providerId": "WBLUE",
        "taxTables": {
            "STAT": [
                1
            ]
        }
    }
]
  

Модель данных: taxControl

 [
    {
        "taxTypeId": "FED",
        "taxIndustryDescription": "Federal",
        "taxIndustryLabel": "Federal",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },
    {
        "taxTypeId": "FRAN",
        "taxIndustryDescription": "Franchise",
        "taxIndustryLabel": "Franchise",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },
    {
        "taxTypeId": "STAT",
        "taxIndustryDescription": "State",
        "taxIndustryLabel": "State",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },
    {
        "taxTypeId": "CNTY",
        "taxIndustryDescription": "County",
        "taxIndustryLabel": "County",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },
    {
        "taxTypeId": "TOWN",
        "taxIndustryDescription": "City",
        "taxIndustryLabel": "City",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },
    {
        "taxTypeId": "SCHL",
        "taxIndustryDescription": "School",
        "taxIndustryLabel": "School",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    }
]
  

В taxControlReference вы увидите, что ключ для каждого taxTables значения будет соответствовать taxTypeId в taxControl модели.

Используя эти данные, я пытаюсь получить результат в следующей модели:

 Array<{taxTypeId: string, taxIndustryDescription, options: taxTablesKey[]}>
  

Я делаю это через наблюдаемые:

 // taxControl$ and taxControlReference$ are the observables of returns data from the above models
observable$ = CombineLatest([taxControl$, taxControlReference$]).pipe(
    // this is the part where I am stuck, because if I try to map out just the taxControl$ then it returns last object in the array a total amount of times equal to the length of the array of objects
)
  

Комментарии:

1. Это кажется мне глубоко запутанным способом попытаться описать проблему. Как выглядит ваш ожидаемый результат?

2. @MrkSef Я добавил ожидаемый результат

Ответ №1:

Есть ряд вещей, которые я не могу понять в вашей проблеме. Я прокомментирую некоторые из них здесь:

 taxControlData$: Observable<any> = combineLatest([
  this.taxControlQuery.taxControlService$, 
  this.taxControlReferenceQuery.taxControlReferenceService$
]).pipe(
  map( ([taxControls, taxTables] : [TaxControl[], TaxTable[]]) => {
    // taxControls is an array (TaxControl[]) 
    // are you sure you want to set options on an array? That would be strange
    taxControls.options = taxTables.map(
      // What is taxTables here? Your model above doesn't reflect this
      taxTables => taxTables.map(
        // Here you're create an array of boolean values. 
        // How do you plan to use those?
        options => options === taxTables.taxTypeId
      )
    );
    // You're still inside the RxJS map function, 
    // you must return something or you'll get a stream of void values. 
    return /* ??? */ 
  })
)
  

В общем, я не уверен, чего вы пытаетесь достичь. Вы говорите, что хотите, чтобы ваш вывод выглядел так:

 [
    taxIndustryDescription<string>,
    options<taxTables[]>
]
  

Ваши данные всегда только одноэлементные массивы? Что, если taxControlReferenceService$ выдает

 [
   {
        "taxTypeId": "STAT",
        "taxIndustryDescription": "State",
        "taxIndustryLabel": "State",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },{
        "taxTypeId": "STAT",
        "taxIndustryDescription": "State",
        "taxIndustryLabel": "State",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    },{
        "taxTypeId": "STAT",
        "taxIndustryDescription": "State",
        "taxIndustryLabel": "State",
        "taxControlReferenceCounter": 1,
        "transactionOn": null
    }
]
  

Как теперь должен выглядеть результат?

Обновить

Я все еще не совсем понимаю, чего вы хотите достичь. Может быть, если вы приведете пример вывода, который соответствует вашему примеру ввода. Как, учитывая данные, которые вы уже предоставили, как будет выглядеть результат? Какие части ввода становятся какими частями вывода?

Это должно вывести массив данных, как правило, в описанном вами формате. Я не уверен, насколько это вам поможет, но, может быть, это поможет вам начать? Здесь, я предполагаю, что вы хотите объединить значения во входных данных?

 taxControlData$: Observable<any> = combineLatest([
  this.taxControlQuery.taxControlService$, 
  this.taxControlReferenceQuery.taxControlReferenceService$
]).pipe(
  map( ([taxControls, taxTables] : [TaxControl[], TaxTable[]]) => {
    const output = new Array<any>();
    for(let i = 0; i < taxControls.length; i  ){
      output.push({
        taxTypeId: taxControls[i].taxTypeId,
        taxIndustryDescription: taxTables[i].taxIndustryDescription,
        options: [{/*?taxTablesKey?*/},{/*?taxTablesKey?*/},{/*?taxTablesKey?*/}]
      })
    }
    return output;
  })
)
  

Комментарии:

1. Я отредактировал свой вопрос выше, пожалуйста, дайте мне знать, если это поможет

2. Я обновил свой ответ, все еще не уверен, что это слишком поможет