angular 为路由守卫将一项服务依赖注入到另一项服务中

angular dependency injection of one service into another for route guard

在我的 angular 应用程序中,我有两个服务,一个处理 http 层,另一个只是一个路由守卫,用于实现与第一个服务的状态相关的 canActivate 方法.例如:

backend.service:

@Injectable()
export class BackendService {
    private data: any;
    constructor(private http: Http) {
        console.log('backend service constructor hit');
        this.data = 'initial';
    }
    getData() {
        console.log(this.data);
        return this.data;
    }
    setData(data) {
        // http stuff
        this.data = data;
    }
}

routeguard.service:

@Injectable()
export class RouteguardService implements CanActivate {
    constructor(private backendService: BackendService) { }
    canActivate() {
        return this.backendService.getData() !== 'initial';
    }
}

我认为我在错误的位置提供了一项服务?目前我的 app.moduleproviders 数组中有这两项服务。但是我可以用 console.log 语句告诉 backend.service 当它作为路由的一部分被调用时与组件使用它时分别被新建,所以数据是不同的并且数据尽管已将其设置为组件中的其他内容,但在 canActivate 方法中检查时总是返回 'initial' 。希望我解释清楚了,我还是新手 angular。

我是否需要在不同的位置提供其中一项服务,或者我是否做错了其他事情?感谢您的指点。

尝试将要在 BackendService 中设置的 属性 声明为 static。然后使用 getters 和 setters 来访问它。不要在服务的constructor中初始化它。

@Injectable()
export class BackendService {
    private static data: any = 'initial';
    constructor(private http: Http) {
        console.log('backend service constructor hit');
    }
    get data() {
        console.log(this.data);
        return BackendService.data;
    }
    set data(data: any) {
        // http stuff
        BackendService.data = data;
    }
}

然后您可以使用 getter 和 setter 在外部访问私有静态 data 值。例如在 canActivate 守卫中,

@Injectable()
export class RouteguardService implements CanActivate {
    constructor(private backendService: BackendService) { }
    canActivate() {
        return this.backendService.data !== 'initial';
        // this.backendService.data <-- denotes getter
        // this.backendService.data = 'not-initial'; <-- denotes setter
    }
}

正如问题所理解的那样,您在正确的地方提供服务。尝试看看是否可以解决问题。

我意识到问题是我不小心也在根 app.component 提供程序中包含了 backend.service,这意味着它的子组件将注入一个实例,但是我的路由中的那个文件是从 app.module 提供商注入的,因此存在重复服务和数据差异。

所以解决方案是从 app.component 中删除该服务,并始终由 app.module 提供。