简体   繁体   中英

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.

And here I have a problem.

I currently have 3 entities: Builder, Category and 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)

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 :

{
  "_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 :

"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 ...)

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?

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

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

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

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