代码之家  ›  专栏  ›  技术社区  ›  Antediluvian

将一堆项目推送到服务器

  •  0
  • Antediluvian  · 技术社区  · 6 年前

    TypeError: Object(...)(...).subscribe is not a function

    push(models: Model[]): void {
        from(models).pipe(
                         mergeMap((m: Model) => this.service.push(m)),
                         bufferCount(models.length)
                    ).subscribe(() => log('done'));
    }
    

    我试图实现的是将每个模型并行地推送到服务器。当所有的推送都完成后,我会记录一条消息。

    1 回复  |  直到 6 年前
        1
  •  0
  •   danday74    6 年前

    下面是一些简化的代码,可以满足您的需要。

    console.log 中的语句 ngOnInit 毕竟 答复已完成。

    import { Component, OnInit } from '@angular/core'
    import { PushItService } from './push-it.service'
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent implements OnInit {
    
      public myObservable$
    
      constructor(private pushItService: PushItService) {}
    
      ngOnInit() {
        this.myObservable$ = this.pushItService.push([{id: 1}, {id: 2}, {id: 3}])
        this.myObservable$.subscribe((data) => {
          console.log('data', data)
        })
      }
    }
    

    .服务.ts:

    import { Injectable } from '@angular/core'
    import { HttpClient } from '@angular/common/http'
    import { forkJoin, of } from 'rxjs'
    import { mergeMap } from 'rxjs/operators'
    
    @Injectable({
      providedIn: 'root'
    })
    
    export class PushItService {
      constructor(private http: HttpClient) {}
    
      push(arr) {
        return of(arr).pipe(
          mergeMap(value => forkJoin(value.map(v => this.http.get('http://localhost:3000/random/' + v.id))))
        )
      }
    }
    

    我用这个资源写了这个代码。。。 https://www.learnrxjs.io/operators/combination/forkjoin.html ... 参见示例2

    我们已经测试过了,它可以完美地工作,但是您应该引入一些错误处理。 This will help you too