0
votes

I have a code that gets Requisition data from an external system like so:

init() {
  const requisitionData = this.loginMb().pipe(
    map(response => response.data.token),
    switchMap(loginData => this.getRequisitions(loginData)),
    map(response => response.data),
  );
  requisitionData.subscribe(this.processData);
}

Here is processData()

processData(response: any) {
  const requisitions = response.content.data;
  for (const p of requisitions) {
    const req = new Requisition(); // Requisition is the TypeORM entity
    req.title = p.title;
    req.reference = p.reference;
    // other fields 

    this.repo.save(requisition);
  }

Here's the constructor

@Injectable()
export class RequisitionSync {
  constructor(
    @InjectRepository(Requisition) private readonly repo: Repository<Requisition>,
    private readonly httpService: HttpService,
  ) {}

The problem is inside processData(), this.repo becomes undefined. If I do console.log(this.repo) inside init(), it will not be undefined.

1
I believe this is because subscribe has a different lexical this than the class itself. What happens if you just console.log(this) in the processData method?Jay McDoniel
It outputs SafeSubscriber { ... , here's the whole thing: pastebin.com/s1zPFBfhEdwin
Just as I thought, the subscribe has a different lexical this than the class.Jay McDoniel
One question, shouldn't processData be an async function?troy
I'm actually not sure about this either.Edwin

1 Answers

1
votes

As the lexical binding of this is different in the class versus in the subscribe method, you'll need to find some other way to manage the function. If possible, I would suggest using one more map or a mergeMap and running your this.processData in it, then subscribing afterwards to let the events transpire as they will, essentially creating the callchain as

init() {
  const requisitionData = this.loginMb().pipe(
    map(response => response.data.token),
    switchMap(loginData => this.getRequisitions(loginData)),
    map(response => response.data),
    map(this.processData), // or mergeMap(data => this.processData(data)), your choice
  );
  requisitionData.subscribe();
}