【问题标题】:How do I convert the data from a http.post response json so I can use it in my application?如何转换来自 http.post 响应 json 的数据,以便在我的应用程序中使用它?
【发布时间】:2017-12-22 20:44:55
【问题描述】:

我对 Web 开发和 Angular 还很陌生,所以我确定我遗漏了一些明显的东西,但我无法弄清楚。

以下是相关代码:

@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 表。

就像我说的,我是新手,所以如果你能具体一点,甚至在你的回复中添加代码 sn-p,我将非常感激。

谢谢

【问题讨论】:

    标签: javascript json angular http post


    【解决方案1】:

    这是我的方法的外观,它通常在服务中:

    服务

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

    注意方法返回类型和 return 语句从方法返回 Observable。

    组件

    订阅然后在这样的组件中:

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

    【讨论】:

    • 我使用第二种方法只是为了让某些东西正常工作。我不得不将最后一行更改为this.permits = res.json();,但这有效。谢谢!我会尝试将其更改为服务,因此这是最佳做法,但它现在可以正常工作。
    【解决方案2】:

    Web 开发愉快!

    首先,您需要将 HTTP 功能转移到服务中。这是最佳实践,因为不同的模块可以使用服务的不同功能,而不是与一个组件紧密耦合(就像您当前所做的那样)。有关服务的更多信息,请参阅Angular docs。

    在将数据分配给对象以以 HTML 格式打印时,您可以简单地通过 .subscribe 函数分配数据,如下所示:

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

    this.recipes 将在您的组件中设置为一个变量,您可以使用它来设置订阅中的data(到 HTTP 响应)。

    之后,如果您的数据包含多个具有相似结构的 json 对象,则使用 Angular 指令 ngFor* 遍历响应数据并将其打印到您的 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>
    

    如果您只是想在一个简单对象上打印数据,您可能已经知道这一点,只需使用&lt;any element you want&gt;{{ yourComponentVariableName }}&lt;/any element you want&gt; 将数据打印到您的 HTML 中。

    IRecipe[] 存在的原因(如果您想知道的话)是因为在接口前面加上 I 是 Angular 中命名接口的约定。这个接口可以定义你的数据的模型,如下图:

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

    有关接口的更多信息,请访问TypeScript's official documentation。

    一切顺利。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      相关资源
      最近更新 更多