2017-04-01 4 views
1

내가 관찰 가능한의 사용을 이해하기 위해 노력하고있어,각이 관찰 다음

모든 단순한 경우 괜찮습니다,하지만 한 경우에 나는 여러 이미지를 압축하고 싶습니다.

나는 이미지를 압축하는 ng2-img-tools

방법을 사용하고 있습니다. 이렇게하면 maxSizeInMB로 지정된 특정 fileSize에 맞을 때까지 이미지의 품질이 감소합니다 ( ). ignoreAlpha를 true로 설정하면 png 이미지의 알파 채널을 무시하고 압축합니다 (권장하지 않음 - 알파 채널이 손실되어 결과 이미지가 원본 이미지와 다를 수 있음). 주어진 모든 파일에 대해 onNext는 모든 것이 계획대로되었을 때 파일을 받거나 무엇인가가 잘못되어 오류 개체를 수신한다는 것을 관찰 결과로 반환합니다.. 내 코드에서

, 나는 다음과 같은 일을 해요 :

compressImages(filesToUpload:File[]):Observable<any> { 
    if (filesToUpload && filesToUpload.length > 0) { 
     return this.ng2ImgToolsService.compress(filesToUpload,GlobalService.MAX_FILE_SIZE_MB).map(response => { 
     console.log("response is"); 
     console.log(response) 
     return response; 
     }); 
    } 
    return Observable.of("no_image").map(response => "no_image"); 

    } 


this.imageService.compressImages(filesToUpload).flatMap(result => { 
      console.log(result) 
      return this.http.post(...); 
     } 
    ).catch(UtilsService.handleError); 

문제가 결과 만 반환 한 파일입니다, 난 내가 어딘가에 result.next()를 사용해야합니다 알고 있지만 내가 어떻게 아무 생각이 없습니다.

답변

1

문제는 다른지도를 수행하지 말고 기능에 subscribe이 필요하다는 것입니다. 당신이 관찰에 가입하면, 당신은 암시 적으로 결과로 onNext()의 값을 수신하고

this.imageService.compressImages(filesToUpload).subscribe(
    result => { 
     // this contains the value of onNext() 
     console.log(result) 
     return  this.imageService.compressImages(filesToUpload).subscribe(
    result => { 
     // this contains the value of onNext() 
     console.log(result) 
     return this.http.post(...); 
    }, error => { 
     // error 
    } this.http.post(...); 
    }, error => { 
     // error 
    } 

more info on subscribing

편집


모든 수집하려는 경우 스트림의 항목을 하나의 목록으로 조작하면 toList()을 다음과 같이 사용할 수 있습니다.

this.imageService.compressImages(filesToUpload).toList().subscribe(
    result => { 
     // this contains all values from the stream 
     console.log(result) 
     return this.http.post(...); 
    }, error => { 
     // error 
    } 
+0

답변 해 주셔서 감사합니다.하지만 어떻게 모든 next() 값을 "루프 오버"합니까? –

+1

@DanyY가 이미 반복 작업을하고 있지 않습니까? 구독은 스트림에 입력 될 때마다 람다 함수를 적용하므로 전달 된 함수가 모든 onNext에 적용됩니다. –

+0

감사합니다! 이제는 상황이 마침내 시작되고 있습니다. 결과가 나올 때 서버에 직접 게시하고 있기 때문에 제 경우에는 발생하지 않습니다. 하지만 별도의 테스트에서 정확히 말한 것처럼 작동합니다. 모두 완료되어 서버에 게시 될 때까지 기다리는 방법이 있습니까? –