2017-12-22 3 views
1

저는 웹 개발과 Angular에 대한 새로운 지식을 가지고 있습니다. 그래서 나는 명백한 것을 놓치고 있다고 확신하지만, 이것을 이해할 수는 없습니다.응용 프로그램에서 사용할 수 있도록 http.post 응답 json에서 데이터를 변환하는 방법은 무엇입니까?

@Component({ 
    selector: 'app-search-permits', 

    templateUrl: 'search.permits.html', 
}) 
export class SearchPermitsComponent { 
    apiRoot: String = 'http://localhost:8080/pzapp-servlet'; 

    constructor(public http: Http) {} 

    test() { 
    console.log('GET'); 
    const url = `${this.apiRoot}/controlleretax?message=getMstx`; 
    this.http.post(url, 'getMstx').subscribe(res => console.log(res.json())); 
    } 
} 

이 브라우저 콘솔에 좋은 JSON을 인쇄 :

다음은 관련 코드입니다. json의 데이터를 객체 (아마도 ArrayList?)에 할당하여 html로 테이블에 데이터를 표시 할 수 있습니다.

중요한 점은 Angular Material2 테이블을 사용하고 있습니다.

내가 말했듯이, 당신이 구체적 일 수도 있고 응답에 코드 스 니펫을 추가 할 수 있다면 정말 고맙겠습니다.

감사

다음

답변

4

내 방법은 모양과 일반적으로 서비스에 포함되는 것 :

서비스

getMovies(): Observable<IMovie[]> { 
    return this.http.get<IMovie[]>(this.moviesUrl) 
        .pipe(
         tap(data => console.log(JSON.stringify(data))), 
         catchError(this.handleError) 
        ); 
} 

공지 메소드 반환 형식과 return 문 관찰을 반환 메서드에서. (가) 구독

구성 요소

는 다음과 같이 구성 요소에서 다음입니다 :

getMovies(): void { 
    this.movieService.getMovies() 
     .subscribe(
      (movies: IMovie[]) => this.movies = movies, 
      (error: any) => this.errorMessage = <any>error); 
} 

또는

이 같은 것을 엉망으로하지 않으려면 ... 선언하고 변수를 지정하면됩니다.

permits: Permits[]; 

    test() { 
    console.log('GET'); 
    const url = `${this.apiRoot}/controlleretax?message=getMstx`; 
    this.http.post(url, 'getMstx').subscribe(res => { 
     console.log(res.json()); 
     this.permits = res; 
    }); 
    } 
+2

나는 두 번째 방법을 사용하여 작동하는 것을 얻었습니다. 나는 마지막 줄을'this.permits = res.json(); '으로 변경해야했지만 효과가 있었다. 감사! 서비스로 변경하려고 노력할 것이므로 최선의 방법이지만 지금은 작동 중입니다. – Richard

1

행복한 웹 개발!

먼저 HTTP 기능을 서비스로 이동해야합니다. 이는 다른 모듈이 서비스의 여러 기능을 사용할 수 있으므로 (현재 수행중인 것처럼) 한 구성 요소와 밀접하게 결합되는 것과는 반대되는 모범 사례입니다. 서비스에 대한 자세한 내용은 Angular docs에 나와 있습니다.

.subscribe((data: IRecipe[]) => this.recipes = data); 

this.recipes이 같은 구성 요소에 설정됩니다 : 개체에 데이터를 할당 측면에서

는 HTML에서 /, 당신은 단순히이 같은 .subscribe 기능을 통해 데이터를 할당 할 수 있습니다로 인쇄하기 변수를 사용하여 data을 구독에서 (HTTP 응답으로) 설정할 수 있습니다.

그런 다음 Angular 지시문 ngFor*을 사용하여 응답 데이터를 반복하고 데이터에 유사한 구조의 여러 json 객체가있는 경우 HTML에 인쇄하십시오.예가 아래에 볼 수 있습니다 :

<div class="cell small-12 medium-3" *ngFor="let recipe of recipes"> 
    <ul class="recipe-list"> 
    <li class="recipe"> 
     <h2 class="recipe-title">{{ recipe.name }}</h2>  
     <img class="recipe-image" src="{{ recipe.image }}"> 
     <div class="recipe-details"> 
      <p>{{ recipe.cookingTime }}</p> 
      <p>{{ recipe.mainIngredients }}</p>  
     </div> 
    </li>  
    </ul> 
</div> 

당신이 단순한 개체의 데이터를 인쇄 할 경우, 당신은 아마 이미 당신의 HTML로 데이터를 출력 할 <any element you want>{{ yourComponentVariableName }}</any element you want>를 사용하여이 알고있다.

I 접두사 인터페이스가 각도로 인터페이스 이름을 지정하기 때문에 이유는 IRecipe[]입니다 (궁금한 사항이있는 경우). 아래 그림과 같이이 인터페이스는, 데이터의 모델을 정의 할 수 있습니다 : 인터페이스에

export interface IRecipe { 
    name: String, 
    cookingTime: String, 
    mainIngredients: Array<String>, 
    ingredients: Array<Object>, 
    image: String 
} 

자세한 내용은 TypeScript's official documentation에서 찾을 수 있습니다.

모두 최고입니다.

관련 문제