Circular dependence on ES6 classes using Angular

3

Hello!

I have a circular dependency problem in an Angular project (4.3.X).

In the app/models directory there are several files that represent the models received by the API.

Scenario:

// center.ts
import {User} from './user';

export class Center {
  name: string;
  users: User[];

  constructor(data: any = {}) {
    this.name = data.name;
    this.users = (data.users || []).map(user => new User(user));
  }
}


// user.ts
import {Center} from './center';

export class User {
  name: string;
  center: Center | null;

  constructor(data: any = {}) {
    this.name = data.name;
    this.center = data.center ? new Center(data.center) : null;
  }
}

Obviously, this produces a circular dependency.

How could I solve it?

Thanks!

    
asked by Óscar 24.08.2017 в 12:42
source

1 answer

0

My solution has been to relate the models in the service and not in the constructor of each model. So the models would look like this:

// center.ts
import {User} from './user';

export class Center {
  name: string;
  users: User[] = [];

  constructor(data: any = {}) {
    this.name = data.name;
  }
}


// user.ts
import {Center} from './center';

export class User {
  name: string;
  center: Center | null = null;

  constructor(data: any = {}) {
    this.name = data.name;
  }
}

And the User service in this way:

// user.service.ts
// [...]
export class UserService {
  // [...]
  getUsers(): Observable<User[]> {
   this.http.get('/users/end/point')
     .map(body => body.json())
     .map(usersData => usersData.map(userData => {
       return createInstance(userData);
     });
  }
}

function createInstance(data: any): User {
  if (!data) { return null; }

  const user = new User(data);

  if (data.center) {
    // Esto no crea una dependencia circular
    user.center = new Center(data.center);
  }

  return user;
}
    
answered by 25.08.2017 / 10:00
source