I have created an API using laravel to check if an email existed in database or not.
/**
*
* @param string $email
*/
public function checkUserEmail($email)
{
$userCount = User::where('email', $email);
if($userCount->count()){
return response()->json("true");
}else{
return response()->json("false");
}
}
I have tested this API in postman and it works as expected
But, when I have use it in frontend it return an object not string!!
Frontend:
checkUserEmail(email : string){
return this.http.get<any>("http://127.0.0.1:8000/api/auth/user-email/" email);
}
CodePudding user response:
In order to get the returned string using HttpClient in Angular you have to subscribe to Observable that returns.
Or you can do the async way using firstValueFrom from RxJS. Notice that response is in string because contains quotes ("false"), is better to just send true or false as boolean.
Here's the example:
public checkUserEmail(email: string): Observable<string> {
return this.http.get("http://127.0.0.1:8000/api/auth/user-email/" email)
.pipe(
map((response: string) => response as string),
catchError( (errorObject) => {
return throwError(() => errorObject);
}
)
);
}
And now you can call this function subscribing or using async way:
Subscribe way (don't forget to unsubscribe):
checkIfEmailIsInDatabase(email: string): void {
this.checkUserEmail("[email protected]").subscribe(
(response: string) => {
// Do your stuff here, like setting variables or whatever
console.log("Response: ", response);
}
)
}
Async way:
async checkIfEmailIsInDatabase(email: string): Promise<void> {
let responseFromServer: string = await firstValueFrom(this.checkUserEmail(email));
console.log("Response from server: ", responseFromServer);
}
Hope it helps.
CodePudding user response:
In Angular the return type of the httpClient's methods are Observables. So in your client code you have to subscribe to the observable. I also suggest so change "any" to string