Preston So의 책 , Decoupled Drupal in Practice에서 시작하여 jsonapi를 사용하여 Drupal 8의 콘텐츠를 Angular 7 앱으로 가져 오는 방법을 배우려고합니다 . 관계에서 자원을 얻는 방법을 보여주는 것보다 부족합니다.
jsonapi 사양은 별도의 호출없이 노드에서 관련 리소스를 가져올 수있는 포함 기능을 제공합니다.
사용 에 http : // localhost를 / jsonapi / 노드 / 기사 /는 MYUUID 포함 = field_image 선물이 일반적인 형식에서 좋은의 JSON 객체입니다.
jsonapi
data
--attributes
--relationships
included
포함 된 부분을 가져 오려고하는데 ArticleService가 데이터의 내용 만 가져 오며 포함 된 부분도 가져오고 싶습니다.
내 article.ts
export class Article {
attributes: object;
relationships: object;
included: object;
}
내 article.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { Article } from '../articles/article';
import { Image } from '../articles/image';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
}
@Injectable({
providedIn: 'root'
})
export class ArticleService {
private articlesUrl = 'http://localhost/jsonapi/node/article';
constructor(private http: HttpClient) {}
getArticle(id: string): Observable<Article>
{
if (id) {
return this.http.get<Article>(this.articlesUrl + '/' + id + '?include=field_image', httpOptions)
.pipe(
map(res => res['data'])
)
.pipe(
catchError(this.handleError([]))
);
}
}
private handleError<T> (result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
}
}
}
그래서 내 첫 번째지도 기능은 본문에서 데이터 객체를 검색합니다. 나는 그것을 확대 할 수있을 것입니다. 내가 설정 시도 map(res => res['body'])
후, map(res => res[''])
어떤 객체를 반환한다. rxjs / operators를 읽으면 mergeMap, concatMap과 같은 일부 연산자는 응답 본문 전체의 내용을 얻는 방법을 이해하지 못하기 때문에 실패합니다. 내 검색 결과에 도움이되는 것 같지 않은 결과를 얻었으므로 전체 응답을 얻는 방법에 대한 포인터를 찾고 있습니다.
article.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { Article } from '../articles/article';
import { Image } from '../articles/image';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
}
@Injectable({
providedIn: 'root'
})
export class ArticleService {
private articlesUrl = 'http://localhost/jsonapi/node/article';
constructor(private http: HttpClient) {}
getArticle(id: string): Observable<Article>
{
if (id) {
return this.http.get<Article>(this.articlesUrl + '/' + id + '?include=field_image', httpOptions);
}
}
private handleError<T> (result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
}
}
}
component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ArticleService } from './article.service'; // import ArticleService service from article.service.ts file
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
// inject ArticleService to the component
constructor(private articleService : ArticleService ) {
this.getArticle(); call getArticle function onInit
}
getArticle() {
const id = 12; // getting article id 12 details
// subscribe to getArticle service method will call HTTP request and return response
this.articleService.getArticle(id).subscribe((response)=> {
// on successful request this block get called
console.log('response body');
console.log(response);
console.log('response actual data');
console.log(response.body);
}, (error)=> {
// on error this block get called like 404, 500 http status
})
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다