Currently facing a coding dilemma: I have an observable that I need to subscribe to and certain requirements must be met:
1 - The registerUser function should only execute after processing the callback data.
2 - If registerTask returns data, I receive an ID and then need to call registerUser, which is also an observable.
3 - In case of an error returned by registerTask, I have to call searchTaskByID to get an ID before calling registerUser.
The issue lies in not wanting to duplicate the code for registerUser within both the data and error branches. Is there a simpler way to ensure its execution regardless of the conditions above? Any suggestions?
Here's the current code snippet I am working with, but it's not functioning as intended:
Angular 2 component:
taskID:String
constructor(
private myService:MyService,
private router:Router
) { }
onClick() {
const task= {
name: this.taskID,
}
const user= {
name: "test",
}
return this.myService.registerTask(task).subscribe(
(data) => {console.log(data)
var taskId = data.taskId
},
(error) => {console.log(error)
this.myService.searchTaskByName(task).subscribe(
(data) => {console.log(data)
var taskId = data.id
},
(error) => {console.log(error)},
()=>{}
);
},
() => this.myService.registerUser(user).subscribe(
(data) => {console.log(data)
var userId = data.id
},
(error) => {console.log(error)}
)
)
}