i want to have 2 function in my userService this is for json server addCountry(data:…
- User
i want to have 2 function in my userService
this is for json server addCountry(data: any): Observable { return this.http.get(
${this.apiUrl}?code=${data.code}) .pipe( switchMap(existingData => { if (Object.keys(existingData).length > 0) { return [{ errorMessage: 'Country is not successfully saved!' }]; } else { return this.http.post(${this.apiUrl}, data).pipe(map(Response => { return { successMessage: 'Country is successfully added!' } })); } }) ); }and this is for springboot java addCountry(country: any): Observable { return this.http.post(
${this.apiUrl}/add-country, country); }now i want to use them at the same time i want to have a button in my html to switch json server or springboot java
- Assistant
To achieve this, you can create a flag variable in your UserService that indicates the current server being used. Here's an example implementation:
In your UserService, define a flag variable to indicate the server being used:
typescriptprivate isJsonServer: boolean = true;Create a function to toggle the server:
typescripttoggleServer(): void { this.isJsonServer = !this.isJsonServer; }Modify the addCountry function to use either the JSON server or Spring Boot server based on the flag value:
typescript - User
how can i toggle this if this is in userService toggleServer(): void { this.isJsonServer = !this.isJsonServer; }
and my main html in a another folder
- Assistant
If your main HTML is in a separate folder and not directly related to the component using the UserService, you can create a separate component to handle the toggle functionality.
-
Create a new component called ToggleServerComponent:
codeng generate component toggle-server -
In the ToggleServerComponent class, import the UserService and define the toggleServer() function:
typescriptimport { Component } from '@angular/core'; import { UserService } from 'path-to-user-service'; @Component({ selector: 'app-toggle-server', template: ` <button (click)="toggleServer()">Toggle Server</button> ` }) export class ToggleServerComponent { constructor(private userService: UserService) {} toggleServer(): void { this.userService.toggleServer(); } }
-