构造函数初始化后未定义Angular 6服务
我通过构造函数将一个服务(ClientProfileService)注入到我的组件中,如下所示:构造函数初始化后未定义Angular 6服务,angular,angular-material2,angular-services,angular-cli-v6,Angular,Angular Material2,Angular Services,Angular Cli V6,我通过构造函数将一个服务(ClientProfileService)注入到我的组件中,如下所示: import { ClientProfileService } from '@app/services/client-profile/client-profile.service'; @Component({ selector: 'app-add-transaction', templateUrl: './add-transaction.component.html', styleUr
import { ClientProfileService } from '@app/services/client-profile/client-profile.service';
@Component({
selector: 'app-add-transaction',
templateUrl: './add-transaction.component.html',
styleUrls: ['./add-transaction.component.scss']
})
export class AddTransactionComponent implements OnInit, AfterViewInit {
...
...
constructor(
private clientProfileService: ClientProfileService
) { }
...
...
public autoCompleteDisplay(clientId?: string): string | undefined {
if (clientId && clientId.trim() !== '') {
// next line produces the error
let profile: IDetailedClientProfile = this.clientProfileService.findClientProfile(clientId);
if (profile) {
return profile.ClientName;
}
}
return undefined;
}
}
如前所述,我正在使用[displayWith]属性在模板中使用角度材质自动完成组件。每当我在下拉框中选择一个值时,所选值(clientId)就会传递给“AutoCompletedDisplay”函数。该部分工作正常,我希望在需要时调用“autoCompleteDisplay”
ClientProfileService的定义如下:
@Injectable({
providedIn:'root'
})
export class ClientProfileService {
private teamClientListSubject: BehaviorSubject<IDetailedClientProfile[]> = new BehaviorSubject(null);
constructor(
private http: HttpClient
) { }
public findClientProfile(clientId: string): IDetailedClientProfile {
let profile: IDetailedClientProfile = this.teamClientListSubject.value.filter(x => x.ClientId === clientId)[0];
return profile;
}
}
所以ClientProfileService在这个特定点上在组件中是未定义的,但是为什么呢?我已经在应用程序的其他几个区域使用完全相同的方法初始化了此服务,没有问题。我认为您的导入是错误的,应该是错误的
import { ClientProfileService } from './services/client-profile/client-profile.service';
尝试在AppModule中注册服务确保您的服务已添加到app.module.ts中的提供商:
import { ClientProfileService } from '@app/services/client-profile/client-profile.service';
...
@NgModule({
declarations: [ ... ],
imports: [ ... ],
providers: [ ..., ClientProfileService],
bootstrap: [AppComponent]
}) export class AppModule { }
您需要的答案可以在此处找到:。
问题在于您使用displayWith的方式,而不是对.ts文件的注入。我认为这似乎是合理的@应用程序是一个网页包别名,对吗?然后,我会假设为uuDirname/uuuuu文件名修改webpacks节点选项也会有所不同。感谢您的回复-尽管导入路径是正确的。路径是在tsconfig.json中设置的别名。还有其他想法吗?只是好奇你有没有弄明白这一点?没有-我现在正在使用一个变通方法,直到我有时间回来再看一遍。我想这可以帮助你:。
import { ClientProfileService } from '@app/services/client-profile/client-profile.service';
...
@NgModule({
declarations: [ ... ],
imports: [ ... ],
providers: [ ..., ClientProfileService],
bootstrap: [AppComponent]
}) export class AppModule { }