0

The service actually get a right value from server (e.g. 1 or 0), but always returned an undefined value when I implemented the service in component. I think the return statement had just compiled before the .then() compiled. How can I fix this issue?

private isDuplicateNik(nik: number): boolean{
    let count: number;
    this.employeeService.isDuplicateNik(nik).then(
        res => {
            count = res;
        }
    );

    return (count > 0 ? false : true);
}
Aldi Unanto
  • 3,626
  • 1
  • 22
  • 30
  • Possible duplicate of [return value after a promise](https://stackoverflow.com/questions/22951208/return-value-after-a-promise) – jonrsharpe Aug 31 '17 at 07:02

2 Answers2

0

since employeeService is an async function. count will be undefined when you return it.

private isDuplicateNik(nik: number) {
    let subject = Subject();
    this.employeeService.isDuplicateNik(nik).then(
        res => {
            subject.next(res > 0 ? false : true);
        }
    );

    return subject;
}

use as:

this.isDuplicateNik.subscribe(res => console.log(res));
Carsten
  • 4,005
  • 21
  • 28
0

The simplest way:

private isDuplicateNik(nik: number): Promise<boolean>{
    return this.employeeService.isDuplicateNik(nik).then(res => res < 0 ? false : true );
}

And even simpler:

private isDuplicateNik(nik: number): Promise<boolean>{
    return this.employeeService.isDuplicateNik(nik).then(res => res > 0);
}

You then use it like:

this.isDuplicateNik(...).then(res => {
    console.log("Res: ", res);
});
Faly
  • 13,291
  • 2
  • 19
  • 37
  • Unfortunately I still get an undefined input – Aldi Unanto Aug 31 '17 at 08:45
  • also returned an error 'Type Promise is not assignable to type boolean', so I've to remove `: boolean` – Aldi Unanto Aug 31 '17 at 08:46
  • I've updated the answer (type mismatch). Are you sure this.employeeService.isDuplicateNik(nik) returns a promise ? Try to log what you get when calling it, by doing: this.employeeService.isDuplicateNik(nik).then(res => console.log(res)); – Faly Aug 31 '17 at 09:05
  • What do you mean by "undefined input" ? – Faly Aug 31 '17 at 09:12
  • Yes, it returns a right value. oh sorry, I mean undefined value. It shows 'undefined' in the console. – Aldi Unanto Aug 31 '17 at 09:18