构造函数初始化后未定义Angular 6服务

问题描述 投票:1回答:4

我有一个服务(ClientProfileService)通过构造函数注入我的组件,如下所示:

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]属性在我的模板中使用Angular Material Autocomplete组件,如in the Angular Material documentation所述。每当我在下拉框中选择一个值时,选定的值(clientId)就会传递给'autoCompleteDisplay'函数。那部分工作正常,我想要它时调用'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;
  }
}

我已经在多个组件中引用了服务中的BehaviorSubject,甚至还有其他函数返回了没有问题的observable,我在这种情况下省略了这些以保持帖子更具可读性。

当调用'autoCompleteDisplay'函数时,我收到一个错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'findClientProfile' of undefined

因此ClientProfileService在此特定点的组件中是未定义的,但为什么呢?我已经使用这种完全相同的方法在应用程序的其他几个区域初始化了这项服务,没有任何问题。

angular angular-material2 angular-services angular-cli-v6
4个回答
0
投票

我认为你的导入是错误的,它应该是

import { ClientProfileService } from './services/client-profile/client-profile.service';

0
投票

尝试在AppModule中注册该服务


0
投票

确保您的服务已添加到app.module.ts中的提供程序:

import { ClientProfileService } from '@app/services/client-profile/client-profile.service';
...
@NgModule({ 
  declarations: [ ... ],
  imports: [ ... ],
  providers: [ ..., ClientProfileService],
  bootstrap: [AppComponent] 
}) export class AppModule { }

-1
投票

你需要的答案可以在这里找到:Cannot read property - displayWith。问题是你使用displayWith而不是注入.ts文件的方式。

© www.soinside.com 2019 - 2024. All rights reserved.