Angular 5:模型之间检测到循环依赖关系

时间:2018-03-02 15:20:18

标签: angular model warnings circular-dependency

我因为这个错误而被困了几天,我不知道如何解决它。

我的应用中有2个型号:UserTeam

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

}

当用户登录时,我获得了他的团队信息。像这样,我可以直接从用户做user.getSettings(),并获得这些设置和团队的合并数组。

另一方面,当我展示一个团队时,它可以有一些用户。

但有了这个,我收到了一个警告:

WARNING in Circular dependency detected: src/app/_models/user.ts -> src/app/_models/team.ts -> src/app/_models/user.ts

是否可以保留此逻辑并避免循环依赖性警告?

非常感谢!

2 个答案:

答案 0 :(得分:0)

几天后,我终于创建了第三个模型“ LoggedUser” ,该模型扩展了我的“ User” 模型,并具有“ team:Team “ 属性:

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

答案 1 :(得分:-1)

  

是否可以保留此逻辑并避免循环依赖性警告?

通过将此添加到angular-cli.json,您可以摆脱警告。

    "defaults": {

    "build": {

        "showCircularDependencies": false 
    }
  }