Angular 4 Integration for FOSUserBundle User Management

I am currently working on a project that involves Angular5 and Symfony2.8! My goal is to retrieve all the users from the FOSUserBundle Class in Symfony and display them in Angular.

The Symfony part is functioning correctly https://i.sstatic.net/Nos3W.png

However, I am encountering issues with the Angular implementation https://i.sstatic.net/KvKhu.png

Upon researching the error, I discovered that the retrieved JSON data from Symfony does not align with the model class I created in Angular

This is the model class Marisupilami.ts (which represents my FOSUserBundle Class in Symfony) :

export class Marisupilami {
  constructor(
    public id,
    public username: string,
    public username_canonical: string,
    public email: string,
    public email_canonical: string,
    public enabled: boolean,
    public password: string,
    public last_login: string,
    public roles: Array<any>,
    public friends: Array< any >,
    public race: string,
    public famille: string,
    public nourriture: string,
    public age: string
  ) {}
}

Marsipularmi-c.service.ts:

import { Injectable } from "@angular/core";
import { Http, Response, Headers } from "@angular/http";
import { Observable } from "rxjs";
import { Marisupilami } from "./Marisupilami";
import "rxjs/add/operator/catch";
import "rxjs/add/operator/map";
import "rxjs/add/observable/throw";
import "rxjs/add/operator/do";

@Injectable()
export class MarsipularmiCService {
  constructor(private _http: Http) {}
  private uri = "http://127.0.0.1:8000/Action/api/users";

  getUsers(): Observable<Marisupilami[]> {
    const headers = new Headers();
    return this._http
      .get(this.uri, { headers: headers })
      .map(res => <Marisupilami[]>res.json())
      .do(data => console.log("All: " + JSON.stringify(data)))
      .catch(this.handelError);
  }
  private handelError(error: Response) {
    return Observable.throw(error.json().errors || "server error");
  }
}

Component code ts Affichage.component.ts :

import { Component, OnInit } from "@angular/core";
import { Marisupilami } from "../Marisupilami";
import { MarsipularmiCService } from "../marsipularmi-c.service";

@Component({
  selector: "app-affichage",
  templateUrl: "./affichage.component.html",
  styleUrls: ["./affichage.component.css"]
})
export class AffichageComponent implements OnInit {
  users: Marisupilami[];
  errorMessage: string;
  constructor(private _userService: MarsipularmiCService) {}

  getUsers() {
    console.log("hello");
    this._userService
      .getUsers()
      .subscribe(
        (users: Marisupilami[]) => (
          (this.users = users), error => (this.errorMessage = <any>error)
        )
      );

    console.log(this.errorMessage);
    console.log("in the get");
  }

  ngOnInit() {
    this.getUsers();
  }
}
Component code html Affichage.component.html :

Hello Users
<h1 class="text-primary">Users </h1>

<div *ngFor="let p of  users">

  <div class="panel">
    <br>
    <br>
    <br>
    <div class="panel-header">
      {{p.username}}
    </div>

    <div class="panel-body">
      {{p.race}}
    </div>

  </div>

</div>

Is there a specific way to represent the FOSUserBundle class in Angular? Or is there an alternative method to achieve this?

Answer №1

modify the function as shown below:

fetchUsers() {
    this._userService.fetchUsers()
      .subscribe(
        (data: Marisupilami[]) => {
             this.users = data;
        },
        error=>{
            this.errorMessage = <any>error;
        }
      );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding flair to a object's value in React JS

In my React JS file, I have a map function that I am using to populate a select dropdown with options. const options = response.map(k => ({ value: k.id, label: k.description ? `${k.name} - ${k.description}` : k.name, })); I ...

Exploring the depths of nested objects within HTML for Angular programming

I am currently working with a data structure that is defined as follows: app_list = ["app_1", "app_2"] data["results"] = { "app_1": [ {"key":1}, {"key":2} ], "app_ ...

The ComponentFactory<any> 'DynamicComponent' cannot be associated with undefined

After researching how to render an MVC View into Angular 2, I came across this helpful directive export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> { const cmpClass = class Dynamic ...

TS - decorator relies on another irrespective of their position within the class

Is it possible to consistently run function decorator @A before @B, regardless of their position within the class? class Example { @A() public method1(): void { ... } @B() public method2(): void { ... } @A() public method3(): void { ... } } In the sc ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

Waiting for a response in Typescript before running a function

Is there a way to execute a function after the response is completed without using setTimeout()? I am facing an issue with uploading large files where the waiting time is insufficient. this.orderTestService.orderObservable$ .pipe(untilDestroyed(this)) ...

Bootstrap flex: on a single row, one column spans the entire height while the other contains elements that are vertically aligned in the center

I'm having trouble with Bootstrap 4 as I try to vertically align the elements of the right column and create a full-height column on the left with just a background color. I've come across many posts discussing similar issues, but none specific t ...

Angular2: Issue encountered while processing click event

When I click a button on my client application, it sends a request to the server I created using Express. The request handler in the server simply logs 'Delete from server' every time the button is clicked. I am encountering these errors when cl ...

Are there any solutions to refresh a page by clicking a button in next.js?

I am currently learning how to work with next.js and I'm facing an issue where I need to reload my page to make a new API request. As a beginner, I'm not sure how to achieve this. I've tried a few methods but none of them seem to work. Below ...

Encountering difficulties in generating a personalized Angular Element

Currently, I am in the process of developing a custom Component that needs to be registered to a module. Here is how it is being done: app.module.ts import { createCustomElement } from "@angular/elements"; @NgModule({ declarations: [ExtensionCompone ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

Issue during deployment: The type 'MiniCssExtractPlugin' cannot be assigned to the parameter type 'Plugin'

I'm working on deploying a Typescript / React project and have completed the necessary steps so far: Created a deployment branch Installed gh-pages for running the deployed application Added a deploy command as a script in the package.j ...

What steps can I take to improve my code and fix lint errors?

I've been working on creating test cases for a switch case scenario, and so far I have two test cases in place. However, I'm encountering a lint error that requests me to update or refactor the function in order to avoid duplicating code. Since m ...

Encountering issues with utilizing Eeflector within a custom interceptor in NestJS. Module import error preventing functionality

I've been working on developing an interceptor for my NestJs application. My goal is to include some metadata in my controller method and then retrieve this data in my interceptor. So, I created my interceptor along with a custom decorator to add the ...

Building a customizable class from scratch

I am currently working on developing configurable classes that come with default values, but allow for configuration changes if needed. The concept involves creating an instance of a class by calling its type specified in the static properties of the Test ...

Is it advisable to choose Ionic or solely Angular when creating a cross-platform app with capacitor?

I am excited to embark on a project to create a versatile software application that can be run as a web app, android app, iOS app, and even potentially as a desktop application. Capacitor offers the promise of achieving this with just one code base. As I p ...

After upgrading from angular-cli version 4 to version 7, the npm installation process stops working

I have been working on transitioning my Angular4 project to Angular7. Here are the steps I took in order to make this conversion: I first uninstalled the older version of angular-cli Next, I installed the latest updated version of angular-cli However, up ...

What is the best way to update my TypeScript array with new values in real-time?

Looking to dynamically populate my pieChartColors array so that it resembles the following structure: public pieChartColors:Array<Color> = [ { backgroundColor: '#141C48' }, { backgroundColor: '#FF0000' }, { backgroundColor: ...

TSDX incorporates Rollup under the hood to bundle CSS Modules, even though they are not referenced

I have recently developed a React library with TSDX and you can find it here: https://github.com/deadcoder0904/react-typical This library utilizes CSS Modules and applies styles to the React components. Although the bundle successfully generates a CSS fi ...

Can we handle optional properties that are contingent on a boolean in the type?

My current scenario involves a server response containing a boolean indicating success and optional data or error information. type ServerResponse = { success: boolean; data?: { [key: string]: string }; err?: { code: number, message: string }; } Dea ...