Angular 16.2.0 Signal报错TypeError: this.customers不是函数求助
问题修复:TypeError: this.customers is not a function
问题根源
你把this.upsertCustomer直接传给RxJS的tap操作符时,方法的this上下文丢失了——此时this不再指向当前的服务实例,而是RxJS内部的执行上下文(Object),导致无法正确访问到你定义的customers信号,所以报错说它不是函数。
修复方案
以下三种方式任选其一即可:
方式1:用箭头函数绑定上下文
在tap中通过箭头函数调用upsertCustomer,确保this指向当前服务实例:
onUpdateCustomer(customer: Customer): Observable<Customer> { console.log('onUpdateCustomer') return this.httpClient.put<Customer>(`${this.url}/${customer.id}`, customer) .pipe( tap(customer => this.upsertCustomer(customer)), //catchError(this.handleError), ) }
方式2:在构造函数中绑定方法
在服务的构造函数里,将upsertCustomer的this强制绑定到当前实例:
constructor(private httpClient: HttpClient) { this.upsertCustomer = this.upsertCustomer.bind(this); }
修改后可以继续使用tap(this.upsertCustomer)的写法。
方式3:将upsertCustomer改为箭头函数
箭头函数会自动捕获当前上下文的this,直接把内部方法定义为箭头函数即可:
private upsertCustomer = (customer: Customer) => { console.log('upsertCustomer') const index = this.customers().findIndex(item => item.id === customer.id) if (index === -1) { this.customers.mutate(customers => customers.push(customer as CustomerProxy)) } else { this.customers.mutate(customers => customers[index] = customer as CustomerProxy) } }
额外优化
你可以简化mutate的写法:添加新客户时,直接用push代替展开数组,逻辑更简洁。
内容的提问来源于stack exchange,提问作者SwHeroCat
相关产品推荐
相关产品推荐

