Angular2 http.get (), map (), subscribe () 및 관찰 가능한 패턴-기본 이해
이제 3 개의 링크가있는 초기 페이지가 있습니다. 마지막 '친구'링크를 클릭하면 적절한 친구 구성 요소가 시작됩니다. 거기에서 friends.json 파일에 눌린 내 친구 목록을 가져오고 싶습니다. 지금까지 모든 것이 잘 작동합니다. 그러나 나는 여전히 RxJ의 Observable, Map, Subscribe 개념을 사용하는 angular2의 HTTP 서비스에 대한 초보자입니다. 나는 그것을 이해하고 기사를 거의 읽지 않았지만 실제 작업에 들어가기 전에는 그 개념을 제대로 이해하지 못할 것입니다.
여기에 이미 HTTP 관련 작업을 제외하고 작동하는 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:
- Observables vs promises - https://egghead.io/lessons/rxjs-rxjs-observables-vs-promises
- Creating-an-observable - https://egghead.io/lessons/rxjs-creating-an-observable
- RxJS In-Depth https://www.youtube.com/watch?v=KOOT7BArVHQ
- Angular 2 Data Flow - https://www.youtube.com/watch?v=bVI5gGTEQ_U
Christoph Burgdorf also wrote some great blog posts on the subject:
- http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
- http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
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
andmap
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 thesubscribe
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);
'development' 카테고리의 다른 글
Android 에뮬레이터는 검은 색 화면 외에는 아무것도 표시하지 않으며 adb 장치는 "장치 오프라인"을 표시합니다 (0) | 2020.05.29 |
---|---|
자바 다중 상속 (0) | 2020.05.29 |
자식 버전 제어를 사용하여 파일의 권한 만 업데이트하고 커밋 (0) | 2020.05.29 |
Express에서 NODE_ENV 란 무엇입니까? (0) | 2020.05.29 |
PHP에서 키에 배열 복사 값 (0) | 2020.05.29 |