问题
I'm stuck for few days with this error, and I don't know how to solve it.
I have 2 models in my app : User
and Team
.
user.ts :
import { Team } from './team';
export class User {
id: string = null;
name: string = null;
email: string = null;
settings: any = {};
team: Team = null;
constructor(json?: Object){
var defaultSettings = {};
if(json){
this.id = json['id'] || null;
this.name = json['name'] || null;
this.email = json['email'] || null;
this.settings = json['settings'] || {};
this.team = new Team(json['team']) || null;
}
}
getSettings(){
return Object.assign(this.team.settings, this.settings);
}
team.ts
import { User } from './user';
export class Team {
id: string = null;
name: string = null;
settings: any = {};
users: User[] = [];
constructor(json?: any){
if(json){
this.id = json['id'] || null;
this.name = json['name'] || null;
this.settings = json['settings'] || {};
if(json['users']) json['users'].forEach(user => this.users.push(new User(user)));
}
}
}
When the user is logged in, I got his infos with the team. Like that, I can do user.getSettings()
directly from the User, and get a merged array of these settings and the Team.
In the other hand, when I show a Team, it can have some users.
But with that, I got a warning :
WARNING in Circular dependency detected:
src/app/_models/user.ts -> src/app/_models/team.ts -> src/app/_models/user.ts
Is it possible to keep this logic and avoid the Circular dependency warning?
Thanks a lot !
回答1:
After few days, I've finally created a third model "LoggedUser", which extends my "User" model, with the "team: Team" property :
user.ts :
export class User {
id: string = null;
name: string = null;
email: string = null;
settings: any = {};
constructor(json?: Object){
var defaultSettings = {};
if(json){
this.id = json['id'] || null;
this.name = json['name'] || null;
this.email = json['email'] || null;
this.settings = json['settings'] || {};
}
}
}
team.ts :
import { User } from './user';
export class Team {
id: string = null;
name: string = null;
settings: any = {};
users: User[] = [];
constructor(json?: any){
if(json){
this.id = json['id'] || null;
this.name = json['name'] || null;
this.settings = json['settings'] || {};
if(json['users']) json['users'].forEach(user => this.users.push(new User(user)));
}
}
}
loggedUser.ts :
import { User } from './user';
import { Team } from './team';
export class LoggedUser extends User {
team: Team = null;
constructor(json?: Object) {
super(json);
this.team = new Team(json['team']) || null;
}
getSettings(){
return Object.assign(this.team.settings, this.settings);
}
}
回答2:
Is it possible to keep this logic and avoid the Circular dependency warning?
By Adding this to your angular-cli.json you can get rid of the warning.
"defaults": {
"build": {
"showCircularDependencies": false
}
}
来源:https://stackoverflow.com/questions/49072091/angular-5-circular-dependency-detected-between-models