programing

각도 2에서 관측 가능한 데이터를 가져오는 방법

muds 2023. 8. 9. 21:07
반응형

각도 2에서 관측 가능한 데이터를 가져오는 방법

의 결과를 인쇄하려고 합니다.http을 불러들입니다Angular사용.rxjs

다음 코드를 고려합니다.

import { Component, Injectable, OnInit } from '@angular/core';
import { Http, HTTP_PROVIDERS } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
class myHTTPService {
  constructor(private http: Http) {}

  configEndPoint: string = '/my_url/get_config';

  getConfig() {

    return this.http
      .get(this.configEndPoint)
      .map(res => res.json());
  }
}

@Component({
    selector: 'my-app',
    templateUrl: './myTemplate',
    providers: [HTTP_PROVIDERS, myHTTPService],


})
export class AppComponent implements OnInit {

    constructor(private myService: myHTTPService) { }

    ngOnInit() {
      console.log(this.myService.getConfig());
    }
}

결과를 출력하려고 할 때마다getconfig그것은 항상 돌아옵니다.

Observable {_isScalar: false, source: Observable, operator: MapOperator}

비록 내가 대신 json 객체를 돌려주지만.

의 결과를 어떻게 출력합니까?getConfig?

관찰 가능 항목에 가입하고 내보낸 값을 처리하는 콜백을 전달해야 합니다.

this.myService.getConfig().subscribe(val => console.log(val));

Angular는 Angularjs 1.x의 약속 기반 대신 관측 가능한 기반을 기반으로 합니다. 따라서 우리가 다음을 사용하여 데이터를 얻으려고 할 때http당신이 했던 것처럼 약속 대신 관찰 가능하게 돌아옵니다.

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

그런 다음 데이터를 가져와서 뷰에 표시하려면 다음과 같은 RxJs 함수를 사용하여 원하는 형태로 변환해야 합니다..map() function and .subscribe()

.map은 관찰 가능한 (http 요청에서 수신한) 다음과 같은 형식으로 변환하는 데 사용됩니다..json(), .text()Angular의 공식 웹사이트에 언급된 바와 같이,

.()subscribe는 관찰 가능한 반응과 톤을 일부 변수에 등록하여 뷰에 표시하는 데 사용됩니다.

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});
this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

언급URL : https://stackoverflow.com/questions/36395252/how-to-get-data-from-observable-in-angular2

반응형