尽管已经提供了Class:(?)的所有参数,但仍无法解析

时间:2018-06-20 14:58:44

标签: angular dependency-injection ngxs

我目前正在为使用ngxs进行状态管理的服务编写一些测试用例。我似乎无法弄清楚下面的代码出了什么问题:

// auth.service.ts
@Injectable({
    providedIn: 'root'
})
export class AuthService {
    @Select(SessionState) session$;
    constructor(private http: HttpClient, private store: Store) {
    }
}



// session.state.ts
export interface SessionStateModel {
    user: User | null;
    token: string | null;
    state: 'authenticated' | 'guest' | 'invalid.credentials' | 'error' | 'pending';
    response?: HttpErrorResponse | string | any;
}

export const defaultSessionState: SessionStateModel = {
    user: null,
    token: null,
    state: 'guest',
    response: null
};

@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
export class SessionState {
    constructor(private auth: AuthService) {
    }
}


// session.state.spec.ts
describe('should handle login, logout and errors properly', () => {
    let store: Store;
    let backend: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                NgxsModule.forRoot([SessionState])
            ],
            providers: [
                AuthService
            ]
        });

        backend = TestBed.get(HttpTestingController);
        store = TestBed.get(Store);
    });

    afterEach(() => {
        // After every test, assert that there are no more pending requests.
        backend.verify();
    });

    it('should handle successful login', () => {
        // oversimplified...
        expect(true).toBe(true);
    });
});

当我使用ng test运行此命令时,业力返回以下异常: Error: Can't resolve all parameters for SessionState: (?).

这对我来说没有任何意义,因为我已经providing SessionState中的AuthService(即TestBed.configureTestingModule)需要什么。我似乎无法弄清楚我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

您可能缺少@Injectable()服务的SessionState。这也可能引发错误。

@Injectable()
export class SessionState {
    constructor(private auth: AuthService) {
    }
}

答案 1 :(得分:1)

在回答此问题时,如果状态类已注入依赖项,则ngxs不适用于Ivy(但请参见下面的编辑)。您可以通过在tsconfig.json中设置以下编译器选项来关闭Ivy:

{
  "angularCompilerOptions": {
    "enableIvy": false
  }
}

编辑:Ngxs为Ivy提供了migration guide。遵循本指南,除了您的@Injectable装饰器之外,您还需要添加@State装饰器:

@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
@Injectable()
export class SessionState {
    constructor(private auth: AuthService) {
    }
}