Angular中GET请求结果解析为自定义User类失败求助
Hey there, let's work through the two main issues you're hitting here—logging the user object correctly and properly converting the API response into a User class instance.
1. Why you see [Object object] in the console
When you do console.log("User retrieved is " + <User>user), JavaScript converts the user object to a string, and the default string representation of any object is [object Object].
To fix this, you have a few better options:
- Use comma separation in
console.logto print the object directly (this lets you inspect it in dev tools):console.log("User retrieved is ", user); - If you want a readable stringified version for logging, use
JSON.stringifywith indentation:console.log("User retrieved is ", JSON.stringify(user, null, 2)); - Use
console.table(user)to view the object's properties in a neat, organized table.
2. Converting the API response to a User class instance
Right now, res.json() returns a plain JavaScript object—TypeScript's type assertion <User>user only tells the compiler to treat it as a User, but it doesn't actually create an instance of your User class at runtime.
To fix this, you need to explicitly map the plain object to a User instance. Here are two clean approaches:
Option 1: Map directly in the .map() operator
Assuming your User class has a constructor that accepts its core properties:
findUser() { const id = this.getCurrentUser().id; return this.http.get('http://localhost:3000/users/' + id) .map(res => { const userData = res.json(); // Create a new User instance and populate its properties return new User( userData.id, userData.name, // Add all other properties your User class requires ); }) .subscribe((user: User) => { console.log("User retrieved is ", user); // Now this.user is a proper User instance, not a string this.user = user; }); }
Option 2: Add a static fromJson method to your User class
This keeps conversion logic encapsulated in the User class, which is cleaner for larger apps:
// Inside your User class definition export class User { id: number; name: string; // Add other class properties here static fromJson(json: any): User { const user = new User(); user.id = json.id; user.name = json.name; // Map all remaining properties from the JSON object return user; } } // Update your findUser method to use the static method findUser() { const id = this.getCurrentUser().id; return this.http.get('http://localhost:3000/users/' + id) .map(res => User.fromJson(res.json())) .subscribe((user: User) => { console.log("User retrieved is ", user); this.user = user; }); }
Bonus: Fixing the this.user assignment
In your original code, this.user = JSON.stringify(user) turns your user into a string. Unless you specifically need a string representation, assign the actual User instance (like in the examples above) so you can access its properties normally (e.g., this.user.name).
内容的提问来源于stack exchange,提问作者Joseph hooper

