I'm trying to use Angular 7+, RxJS 6+, and the InMemoryAPI to create a mock API for testing my front-end GUI. Here's my "in-memory-data-.service.ts":
export class InMemoryDataService implements InMemoryDbService {
// HTTP POST interceptor
post(reqInfo: RequestInfo) {
console.log('Caught POST:');
console.log(reqInfo);
if (reqInfo.collectionName === 'myApiUrlSign') {
console.log('Return generated myObject');
const reportResponse = new MyObject();
reportResponse.id = reqInfo.utils.getJsonBody(reqInfo.req);
reportResponse.time = new Date();
const response: ResponseOptions = {
body: reportResponse,
status: STATUS.OK
};
const observable = of(response);
console.log('In Memeory data service = ');
console.log(observable);
return observable;
}
return undefined; // Let the default POST handle all others
}
// Example DB Collection
createDb() {
const heroes = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' }
];
return {heroes};
}
}
Then my service is a simple post call:
generateMyObject(myId: string): Observable<MyObject> {
return this.http.post<MyObject>(
this.apiUrl,
JSON.stringify({ myId }),
{ headers: this.headers }
);
}
Finally my component onSubmit function is as follows:
onSubmit() {
const self = this;
const formModel = this.myForm.value;
const obs = this.myService.generateMyObject(formModel.myId);
console.log('On Submit Observer = ');
console.log(obs);
obs.subscribe((data: MyObject) => { // On Next()
console.log('MyObject recieved');
console.log(data);
self.myObject = data;
},
error => console.log(error), // On Error()
() => console.log('Completed')); // On Completed()
console.log(this.myObject);
}
Everything works except my observer next function is never called and the "Completed" function is. The console log inside the "InMemoryDataService" returns the correct observable with the expected "MyObject" value. Although, in my Angular component console.log a different observable is returned. It has the correct MyObject value, but it looks "nested" in 3 parents Observable.source objects. So if I use the following assignment the next() function is called correctly:
const obs = this.reportGenService.generateReport(formModel.orderId)
.source.source.source;
This is super weird and when I hover over the ".source" in my IDE the hint says it's deprecated. How do I get this to work without using multiple ".source" calls? I'm sure I'm missing something, I just don't know what. Your help is greatly appreciated.
reqInfo.utils.createResponse$(). Did you try it ? - Gilsdav