@NgModule({
  declarations: [
    AppComponent
    , DesktopComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    AppRoutingModule,
    )
  ],
  providers: [LoginService, { provide: LocationStrategy, useClass: HashLocationStrategy } ,
    {
      provide: Http,
      useFactory: httpFactory,
      deps: [XHRBackend, RequestOptions, Router, AppComponent]
    }, MasterDataService, PersonService
  ],
  bootstrap: [AppComponent]

})
export class AppModule { }

获取错误错误:没有appcomponent的提供程序!添加deps时:[xhrbackend,requestoptions,router,appcomponent]。
使用本教程https://scotch.io/@kashyapmukkamala/using-http-interceptor-with-angular2来实现拦截器。现在我想从inteceptor类调用appcomponent中的一个方法。
这是拦截器方法,在这里我必须调用appcomponent logout方法
 intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status == 401) {

               localStorage.clear();
             this.appComp.logout();

            } else {
                return Observable.throw(err);
            }
        });

应用程序内组件注销方法
logout() {
        console.log(" logging out");
        this.authenticated = false;
        $('#wrapper').attr("style", "display:none");
        this.loginService.logout();
    }

最佳答案

您在这里尝试使用的方法与角度设计原则不一致,服务应该被设计为seperate concern并且应该由不同的组件重用,并且也可以测试。因此,服务不应尝试直接与组件交互。相反,组件应该监听来自服务的响应或事件,然后决定如何响应。
我建议创建一个通用通知服务,用于在整个应用程序中发送内部消息。此服务不限于从侦听器向appcomponent发送消息,但可以重用以在应用程序的各个部分中传递事件。
下面是一个简单通知服务的示例,此服务应该同时注入到拦截器和appcomponent中:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Notification } from './notification';

@Injectable()
export class NotificationService {
    private notificationSubject = new Subject<Notification>();
    public notifications = this.notificationSubject.asObservable();

    notify(notification: Notification): void {
        this.notificationSubject.next(notification);
    }
}

通知类如下所示:
export class Notification {
    message: string;
    status: NotificationStatus;

    constructor(message?: string, status?: NotificationStatus) {
        this.message = message;
        this.status = status;
    }
}

export enum NotificationStatus {
    Success = 0,
    Loading = 1,
    Confirm = 2,
    Error = 3,
    Unauthorized = 4
}

因此,当您要发送消息时,请插入通知服务并调用notify方法:
if (err.status == 401) {
    this.notificationService.notify(new Notification('Unauthorized', NotificationStatus.Unauthorized));
    return Observable.empty();
}

然后,appcomponent可以从通知服务订阅事件:
this.notificationService.subscribe(notification => {
    if(notification.status == NotificationStatus.Unauthorized) {
        //Handle any unauthorized errors here like and call logout() method
    }
});

10-07 14:53