development

Angular2 http.get (), map (), subscribe () 및 관찰 가능한 패턴-기본 이해

big-blog 2020. 5. 29. 22:06
반응형

Angular2 http.get (), map (), subscribe () 및 관찰 가능한 패턴-기본 이해


이제 3 개의 링크가있는 초기 페이지가 있습니다. 마지막 '친구'링크를 클릭하면 적절한 친구 구성 요소가 시작됩니다. 거기에서 friends.json 파일에 눌린 내 친구 목록을 가져오고 싶습니다. 지금까지 모든 것이 잘 작동합니다. 그러나 나는 여전히 RxJ의 Observable, Map, Subscribe 개념을 사용하는 angular2의 HTTP 서비스에 대한 초보자입니다. 나는 그것을 이해하고 기사를 거의 읽지 않았지만 실제 작업에 들어가기 전에는 그 개념을 제대로 이해하지 못할 것입니다.

여기에 이미 HTTP 관련 작업을 제외하고 작동하는 plnkr을 만들었습니다.

Plnkr

myfriends.ts

 import {Component,View,CORE_DIRECTIVES} from 'angular2/core';
 import {Http, Response,HTTP_PROVIDERS} from 'angular2/http';
 import 'rxjs/Rx';
 @Component({
    template: `
    <h1>My Friends</h1>
    <ul>
      <li *ngFor="#frnd of result">
          {{frnd.name}} is {{frnd.age}} years old.
      </li>
    </ul>
    `,
    directive:[CORE_DIRECTIVES]
  })

  export class FriendsList{

      result:Array<Object>; 
      constructor(http: Http) { 
        console.log("Friends are being called");

       // below code is new for me. So please show me correct way how to do it and please explain about .map and .subscribe functions and observable pattern.

        this.result = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result =result.json());

        //Note : I want to fetch data into result object and display it through ngFor.

       }
  }

올바르게 안내하고 설명하십시오. 많은 새로운 개발자들에게 도움이 될 것입니다.


여기가 잘못되었습니다.

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

그것은해야한다:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

또는

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

두 가지 실수를했습니다.

1- 옵저버 블 자체를에 할당했습니다 this.result. 실제로 친구의 목록을 지정하고 싶어 할 때 this.result. 올바른 방법은 다음과 같습니다.

  • 옵저버 블을 구독합니다. .subscribe실제로 Observable을 실행하는 함수입니다. 다음과 같이 세 가지 콜백 매개 변수가 필요합니다.

    .subscribe(success, failure, complete);

예를 들면 다음과 같습니다.

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

일반적으로 성공 콜백에서 결과를 가져 와서 변수에 할당합니다. 오류 콜백은 자명하다. 전체 콜백은 오류없이 마지막 결과를 수신했는지 확인하는 데 사용됩니다. 플 런커에서 성공 또는 오류 콜백 후에 항상 완전한 콜백이 호출됩니다.

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.


Concepts

Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.

What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map, ...). This allows to handle asynchronous things in a very flexible way.

A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

(textValue is the control associated with the filter input).

Here is a wider description of such use case: How to watch for form changes in Angular 2?.

There are two great presentations at AngularConnect 2015 and EggHead:

Christoph Burgdorf also wrote some great blog posts on the subject:

In action

In fact regarding your code, you mixed two approaches ;-) Here are they:

  • Manage the observable by your own. In this case, you're responsible to call the subscribe method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of result">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit, OnDestroy {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.friendsObservable = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result = result);
       }
    
       ngOnDestroy() {
         this.friendsObservable.dispose();
       }
    }
    

    Returns from both get and map methods are the observable not the result (in the same way than with promises).

  • Let manage the observable by the Angular template. You can also leverage the async pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe method.

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of (result | async)">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.result = http.get('friends.json')
                      .map(response => response.json());
       }
    }
    

You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe method.

You can also notice that the map method is used to extract the JSON content from the response and use it then in the observable processing.

Hope this helps you, Thierry


import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

참고URL : https://stackoverflow.com/questions/34671715/angular2-http-get-map-subscribe-and-observable-pattern-basic-understan

반응형