简体   繁体   中英

How do I convert the data from a http.post response json so I can use it in my application?

I'm fairly new to web development and Angular so I'm sure I'm missing something obvious but I can't figure this out.

Here's the relevant code:

@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()));
  }
}

This prints a nice json to my browser console. I want to assign the data in the json to an object (probably an ArrayList?) so I can display the data in a table in html.

If it matters I'm using an Angular Material2 table.

Like I said, I'm new to this so if you could be specific or even add a code snippet to your response I'd really appreciate it.

Thanks

Here is what my method looks like and its normally in a service:

Service

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

Notice the method return type AND the return statement to return the Observable from the method.

Component

The subscribe is then in the component like this:

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

Alternatively

If you don't want to mess with anything like this ... you just need to declare and assign a variable:

  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;
    });
  }

Happy web developing!

Firstly, what you need to do is move your HTTP functionality into a service. This is best practice as different modules can consume the different functionalities of the service, as opposed to it being tightly coupled to one component (as you are currently doing). More information about services is in the Angular docs .

In terms of assigning the data to an object to print out as/in HTML, you can simply assign the data via the .subscribe function like this:

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

this.recipes will be set in your component as a variable which you can use to set the data from your subscription (to the HTTP response).

After this, use the Angular directive ngFor* to iterate through the response data and print it into your HTML if your data contains several json objects with a similar structure. An example can be seen below:

<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>

If you just want to print out the data on a simple object, you probably already know this, just use <any element you want>{{ yourComponentVariableName }}</any element you want> to print out the data into your HTML.

The reason IRecipe[] is there (if you are wondering) is because prefixing interfaces with I is the convention for naming interfaces in Angular. This interface can define the model of your data, as shown below:

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

More information on Interfaces can be found on TypeScript's official documentation .

All the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM