Angular 5中如何利用接口返回值实现路由与消息提示?
Hey there! Let's walk through how to modify your UserService to extract the status and message fields from the login response, show user prompts, and trigger route navigation when login succeeds.
Step 1: Add Required Dependencies
First, we need to inject Angular's Router to handle navigation. If you're using a UI library for user notifications (like Angular Material's MatSnackBar or NG-ZORRO's NzMessageService), you can inject that too—we'll use a native alert here for simplicity, but you can swap it out easily.
Step 2: Updated Service Code
Here's the modified UserServiceService with all the functionality you need:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; // Add HttpHeaders if using httpOptions import { Router } from '@angular/router'; @Injectable() export class UserServiceService { userEmail: string; userPassword: string; // Define httpOptions if you need custom headers (match your original code) private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; // Inject Router alongside HttpClient constructor(private http: HttpClient, private router: Router) { } login(userEmail, userPassword) { const body = { "email": userEmail, "password": userPassword }; this.http.post<{ message: string, status: string }>( '/customer/service/logging', body, this.httpOptions ).subscribe( (response) => { // Show the success message to the user alert(response.message); // Check if status is "success" and navigate to your target route if (response.status === "success") { // Replace '/dashboard' with your actual route path (e.g., '/user-profile') this.router.navigate(['/dashboard']); } }, (error) => { console.error("There Is Something Wrong\nPlease Try Again Later..."); // Show a user-friendly error prompt alert("登录失败,请稍后重试"); } ); } }
Key Details Explained
- Type Safety: We added a type definition
<{ message: string, status: string }>to thepostcall so TypeScript can validate the response structure and give you autocomplete for the fields. - User Notifications: The
response.messageis directly used to show a prompt to the user. If you're using a UI component instead ofalert, just replacealert(response.message)with your component's method (e.g.,this.snackBar.open(response.message, 'Close', { duration: 3000 })forMatSnackBar). - Route Navigation: When
response.statusequals"success", we callrouter.navigate()to send the user to the desired route—just update the path to match your app's routing setup. - Error Handling: We kept your original error log and added a user-facing error prompt to make sure the user knows something went wrong.
Quick Optimization Note
Make sure you've imported RouterModule in your app's root module and set up the target route (like /dashboard) in your routing configuration—otherwise the navigation won't work!
内容的提问来源于stack exchange,提问作者DESH

