Чтобы присвоить значение переменной при подписке на ответ наблюдаемой - PullRequest
1 голос
/ 03 октября 2019

Я хочу присвоить значение ответа переменной ahumode, чтобы получить доступ к значению через класс и после присвоения, вызвать функцию this.loadFloorLayouts ()

ahumode = [];

//1st async api
this.siteService.getParamsEquip(this.buildings.ccus[0].referenceIDs.ahu,"system")
.pipe(switchMap( rows =>{
    return rows.rows.map((m) => {
    // this is a custom function
    let ahuId = this.helperService.stripHaystackTypeMapping(m['id']).split(' ')[0];
    console.log(ahuId)
    //2nd async api
    this.siteService.getPointData(ahuId,"current")  
  })  
})
).subscribe(a => {
   this.ahumode = a[0].val;
   this.loadFloorLayouts(this.buildings.floors);
})

a равно undefined

Если я попробую что-то подобное

ahumode = [];
this.siteService.getParamsEquip(this.buildings.ccus[0].referenceIDs.ahu,"system")
.pipe(switchMap( rows =>{
    return rows.rows.map((m) => {
    let ahuId = this.helperService.stripHaystackTypeMapping(m['id']).split(' ')[0];
    this.ahumode.push(this.siteService.getHisPointData(ahuId,"current"))
    //this.siteService.getPointData(ahuId,"current") 
    this.loadFloorLayouts(this.buildings.floors) 
  })  
})
).subscribe()

, я получу наблюдаемый объект.

Я проверил, что 2-й вызов API также выполняется, но не может присвоить значение переменной

Обновление

Если я только подпишусь на 1-й вызов API

 this.siteService.getZoneParamsByEquip
  (this.buildings.ccus[0].referenceIDs.ahu,"system").subscribe( r => console.log(r))

Это ответ, который я получаю

{meta: {…}, cols: Array(15), rows: Array(1)}
cols: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
meta: {ver: "2.0"}
rows: Array(1)
  0:
  dis: "Dd_350.1-SystemEquip-operatingMode"
  his: "m:"
  id: "r:5d96e1a12d9dd301026a5654"

Я хочу получить идентификатор из этого ответа и сделать 2-й вызов API, используя идентификатор

Update2

Я попытался что-то, как показано ниже, но выполнение не идет внутри канала (switchmapи без ошибок

this.siteService.getZoneParamsByEquip(
    this.buildings.ccus[0].referenceIDs.ahu,"system")
        .pipe(switchMap( rows =>{
              let responses = [];
              rows.rows.map( (m) => {
              let ahuId = this.helperService
                              .stripHaystackTypeMapping(m['id']).split(' ')[0];

              responses.push(this.siteService.getHisPointData(ahuId,"current"))
              })

              forkJoin(responses).subscribe(([results]) => {
                 //check for the results here and assign them to your variable
                 this.ahumode = results
                 this.loadFloorLayouts(this.buildings.floors);
              })
              return this.ahumode;  
            })
    )

Ответы [ 2 ]

2 голосов
/ 04 октября 2019

Я положил объяснения в комментариях.

ahumode = [];

//1st async api
this.siteService.getParamsEquip(this.buildings.ccus[0].referenceIDs.ahu, "system")
   .pipe(
      switchMap(result =>
         // switchMap expects a function that returns a stream, if you're making several API calls,
         // you need to combine them with forkJoin or combineLatest
         forkJoin(
            // here you'll need an array of streams
            result.rows.data.map(m => {

               let ahuId = this.helperService.stripHaystackTypeMapping(m['id']).split(' ')[0];
               console.log(ahuId)

               // the return statement was missing
               return this.siteService.getPointData(ahuId, "current")
            })
         })))
.subscribe(a => {
   this.ahumode = a[0].val;
   this.loadFloorLayouts(this.buildings.floors);
})
0 голосов
/ 03 октября 2019

Пожалуйста, попробуйте ниже код:

ahumode = [];

    //1st async api
         this.siteService.getParamsEquip(this.buildings.ccus[0].referenceIDs.ahu,"system").pipe(switchMap( rows =>{
  return rows.rows.map((m) => {
    his.helperService.stripHaystackTypeMapping(m['id']).subscribe(response=>{
    let authId=response.split(' ')[0];
    console.log(ahuId)
    //2nd async api
    this.siteService.getPointData(ahuId,"current")  
})

  })  
})
).subscribe(a => {
   this.ahumode = a[0].val;
   this.loadFloorLayouts(this.buildings.floors);
})
...