简体   繁体   English

将 JSon 转换为 Angular TypeScript 对象

[英]Converting JSon to Angular TypeScript Object

I am learning the wonderful world of Angular myself, but I am currently experiencing a problem : I want to make a website and to do this I use back spring and front Angular 7.我自己正在学习 Angular 的美妙世界,但我目前遇到了一个问题:我想制作一个网站,为此我使用了 back spring 和 front Angular 7。

And here I have a problem.我有一个问题。

I currently have 3 entities: Builder, Category and Ship.我目前有 3 个实体:Builder、Category 和 Ship。

And my ship has of course a builder attribute (the builder of the ship) a category attribute (hunter ...).我的船当然有建造者属性(船的建造者)和类别属性(猎人...)。

After request to my service.在请求我的服务后。 (Vaisseau.service.ts) (Vaisseau.service.ts)

public host = 'http://localhost:8080';

  constructor(private httpClient: HttpClient) {
  }

  public getVaisseaux(page: number, size: number) {
    return this.httpClient.get(this.host + '/vaisseaus?page=' + page + '&size=' + size);
  } 

He returns the JSon :他返回 JSon :

{
  "_embedded" : {
    "vaisseaus" : [ {
      "nom" : "nomVaisseau",
      "description" : "Description du vaisseau",
      "image" : "http://127.0.0.1/img/Vaisseaux/2.jpg",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/vaisseaus/2"
        },
        "vaisseau" : {
          "href" : "http://localhost:8080/vaisseaus/2"
        },
        "constructeur" : {
          "href" : "http://localhost:8080/vaisseaus/2/constructeur"
        },
        "categorie" : {
          "href" : "http://localhost:8080/vaisseaus/2/categorie"
        },
        "utilisateurs" : {
          "href" : "http://localhost:8080/vaisseaus/2/utilisateurs"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/vaisseaus{&sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/vaisseaus"
    },
    "search" : {
      "href" : "http://localhost:8080/vaisseaus/search"
    }
  },
  "page" : {
    "size" : 5,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

What I call this :我称之为:

public constructeurs: any;
  public pages: Array<number>;
  private currentPage = 0;
  private size = 2;
  private totalPages: number;
  private currentKeyword = '';

  constructor(private constService: ConstructeurService, private router: Router) {
  }

  ngOnInit() {
    this.onGetConstructeurs();
  }

  onGetConstructeurs() {
    this.constService.getConstructeurs(this.currentPage, this.size)
      .subscribe(data => {
        this.constructeurs = data;
        this.totalPages = data['page'].totalPages;
        this.pages = new Array<number>(this.totalPages);
      }, err => {
        console.log(err);
      });
  }

and in my template:在我的模板中:

<table *ngIf="vaisseaux" class="table">
        <!-- Si il n'y a pas de vaisseaux en BDD n'affiche pas le tableau-->
        <thead class="thead-dark">
        <tr>
          <th scope="col">Vaisseau</th>
          <th scope="col">Nom</th>
          <th scope="col">Constructeur</th>
          <th scope="col">Catégorie</th>
          <th scope="col">Action</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let p of vaisseaux._embedded.vaisseaus">
          <td class="col-md-2 align-middle"><img src="{{p.image}}"></td><!-- {{p.image}} -->
          <td class="col-md-2 align-middle text-center">{{p.nom}}</td>
          <td class="col-md-2">{{p.constructeur.nom}}</td>
          <td class="col-md-2">{{p.categorie.nom}}</td>
          <td class="col-md-2 align-middle  text-center">
            <a (click)="voirVaisseau(p)" class="btn btn-primary"><i aria-hidden="true"
                                                                    class="fa fa-plus-circle"></i></a>
            <a (click)="onEditVaisseau(p)" class="btn btn-warning m-2">Modifier</a>
            <a (click)="onDeleteVaisseau(p)" class="btn btn-danger">Supprimer</a></td>
        </tr>
        </tbody>
      </table>

and the following error appears:并出现以下错误:

ERROR TypeError: "_v.context.$implicit.constructeur is undefined"
    View_LstVaisseauComponent_3 LstVaisseauComponent.html:35
    Angular 29
    RxJS 5
    Angular 9
LstVaisseauComponent.html:34:56
    View_LstVaisseauComponent_3 LstVaisseauComponent.html:34
    Angular 15
    RxJS 5
    Angular 9

So I can not get the ship builder and its category .... With JSon :所以我无法获得造船厂及其类别......使用 JSon :

"vaisseau" : {
          "href" : "http://localhost:8080/vaisseaus/2"
        },

I looked on Google other the different ways to load the JSon (interfaces in Angular, or constructors that take as parameter the Json which is browsed as an array ...)我在谷歌上查看了其他加载 JSon 的不同方法(Angular 中的接口,或者将 Json 作为参数的构造函数,作为数组浏览......)

I do not understand where my problem comes from ... On the side of the Back where I have to give parameters to my REST so that it sends each time all the information and not links that point to the entities or on Angular to load the different objects in load from the links?我不明白我的问题来自哪里......在背面的一侧,我必须为我的 REST 提供参数,以便它每次发送所有信息,而不是指向实体或 Angular 的链接以加载从链接加载的不同对象?

After having followed many tutorials on the Internet, I still do not know that it is the best way to convert the JSon Interfaces, Mapper .......在网上看了很多教程后,我仍然不知道转换JSon Interfaces,Mapper是最好的方法.......

Try with this approach by adding observer response in your code like this通过在您的代码中添加观察者响应来尝试使用这种方法

  public getVaisseaux(page: number, size: number) {
    return this.httpClient.get(this.host + '/vaisseaus?page=' + page + '&size=' + size, {
      observe: 'response'
    });
  } 

If it not working ask developer to change the data he return the _embedded should not have _ sign如果它不起作用,请开发人员更改他返回的数据, _embedded不应有_符号

In the end, I used projections that allow me to recover what I want.最后,我使用了可以让我恢复我想要的东西的投影。 This JSON format is due to Spring HATEOAS which, instead of providing the sub-entities, simply sends a link pointing to it.这种 JSON 格式归因于 Spring HATEOAS,它不提供子实体,而是简单地发送指向它的链接。 Many solutions are available on the Internet to work around this "problem" personally I opted for projections.互联网上有许多解决方案可以解决这个“问题”,我个人选择了预测。 Here is a small example for those interested: Back:这是一个给感兴趣的人的小例子:返回:

 @Projection(name = "vaisseauProjection", types = Vaisseau.class)
public interface VaisseauProjection {

    public long getId();
    public String getNom();
    public String getDescription();
    public String getImage();
    public Constructeur getConstructeur();
    public Categorie getCategorie();

}

Front :正面 :

  public getVaisseauxByKeyword(mc: string, sort: string, order: string, page: number, size: number): Observable<PageableVaisseaux> {
    return this.httpClient.get<PageableVaisseaux>(this.host + '/vaisseaus/search/byNomPage?mc=' + mc + '&sort=' + sort + ','
      + order + '&page=' + page + '&size=' + size + '&projection=vaisseauProjection');
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 2:TypeScript / Javascript:将JSON字符串值转换为正确的JSON对象 - Angular 2: TypeScript/Javascript: Converting JSON string value to proper JSON object 将打字稿对象转换为有效的JSON - Converting typescript object to valid JSON Typescript将JSON对象转换为Typescript类 - Typescript converting a JSON object to Typescript class Converting json object to typescript interface causing error in the mock object while unit testing in Angular 11 - Converting json object to typescript interface causing error in the mock object while unit testing in Angular 11 Angular,转换 JSON,Rxjs 操作员,Z9327DAFFB330417F4027934CC9Z5F - Angular, Converting JSON , Rxjs Opertaor, Typescript Angular 2-Json解析为TypeScript对象 - Angular 2 - Json parse to TypeScript Object 将带有字典的 typescript class object 字符串转换为 Z0ECD11C1D7A287401D148A23BBD7A2FZ8 - Converting a typescript class object with dictionary to a JSON string 将带有字典的 typescript class object 转换为 Z0ECD11C1D7A287401D148A23BBD7A2F8 数组 - Converting a typescript class object with dictionary to a JSON array JSON字符串化JSON对象打字稿/角度 - JSON stringify json object typescript / angular 自动将JSON对象映射到TypeScript对象(Angular 2) - Map JSON object to TypeScript object automatically (Angular 2)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM