angular - 问题重构为角度反应式编程
问题描述
我正在尝试重构反应式编程,但遇到了障碍。下面我将发布原始代码和修改后的代码以进行重构。问题是用户名没有显示在网页上。加载页面时,它会在几秒钟后显示“正在加载...”,但它会消失但不会被昵称替换,它应该根据模板代码执行此操作。怎么了?
原始代码 user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders , HttpParams } from '@angular/common/http';
import { User } from '../models/user';
import { tap, map } from 'rxjs/operators';
import { Car } from '../models/car';
@Injectable({ providedIn: 'root' })
export class UserService {
headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'application/json'
});
host = 'http://localhost:8080/';
constructor(private http: HttpClient) { }
register(user: User) {
let params = new HttpParams()
.set('username', user.username)
.set('firstname', user.firstName)
.set('lastname', user.lastName)
.set('password', user.password)
.set('email', user.email)
let options = {headers:this.headers, params:params}
return this.http.post(this.host + 'register', options );
}
getUser(userId:number){
let params = new HttpParams().set('userId', String(userId));
let options = { headers: this.headers, params: params };
return this.http.get(this.host + 'getUserById', options);
}
}
用户页面.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import { User } from '../models/user';
import { ActivatedRoute, ParamMap } from '@angular/router';
@Component({
selector: 'app-user-page',
templateUrl: './user-page.component.html',
styleUrls: ['./user-page.component.css']
})
export class UserPageComponent implements OnInit {
user = new User;
userId:number = null;
subscriptionUserId;
subscriptionUser;
constructor(private userService:UserService, private route: ActivatedRoute) {
this.subscriptionUserId = this.route.paramMap.subscribe((params : ParamMap)=> {
this.userId = parseInt(params.get('userId'));
});
}
ngOnInit() {
this.subscriptionUser = this.userService.getUser(this.userId).subscribe( data => {
this.user.firstName = data[0].firstname;
this.user.lastName = data[0].lastname;
this.user.username = data[0].username;
}, error => {
console.error(error);
})
}
ngOnDestroy(){
this.subscriptionUserId.unsubscribe();
this.subscriptionUser.unsubscribe();
}
}
用户页面.component.html
<body>
<h2>Welcome to User Page</h2>
<div class="containerUser">
<div class="items"><h2 class="sellerUsername"><b>{{user?.username}}</b></h2></div>
<div class="items"><app-star-rating userId="{{userId}}"></app-star-rating></div>
</div>
<app-user-gallery [userId]="userId"></app-user-gallery>
</body>
重构代码 user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders , HttpParams } from '@angular/common/http';
import { User } from '../models/user';
import { tap, map, shareReplay } from 'rxjs/operators';
import { Car } from '../models/car';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class UserService {
headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'application/json'
});
host = 'http://localhost:8080/';
user:Observable<User>;
constructor(private http: HttpClient) { }
register(user: User) {
let params = new HttpParams()
.set('username', user.username)
.set('firstname', user.firstName)
.set('lastname', user.lastName)
.set('password', user.password)
.set('email', user.email)
let options = {headers:this.headers, params:params}
return this.http.post(this.host + 'register', options );
}
getUserById(userId:number){
let params = new HttpParams().set('userId', String(userId));
let options = { headers: this.headers, params: params };
this.user = this.http.get(this.host + 'getUserById', options)
.pipe(
map( response => response as User ),
tap( user => console.log(user) )
);
}
}
用户页面.component.html
<body>
<h2>Welcome to User Page</h2>
<div class="containerUser">
<div class="items" *ngIf="userService.user | async as user$; else loading">
<h2 class="sellerUsername"><b>{{user$.username}}</b></h2>
</div>
<ng-template #loading>Loading...</ng-template>
<div class="items"><app-star-rating userId="{{userId}}"></app-star-rating></div>
</div>
<app-user-gallery [userId]="userId"></app-user-gallery>
</body>
解决方案
以下内容应使您重构的模板与您在模板中使用的*ngIf
andelse
语法一起工作。
查看此 Stackblitz,它基于您的代码,将突出显示您在此处使用的模式:https ://stackblitz.com/edit/angular-nowbcs?file=src%2Fapp%2Fapp.component.ts
您的服务应该有一个调用的方法getUser()
,该方法返回一个Observable<User>
.
getUser(userId): Observable<User> {
let params = new HttpParams().set('userId', String(userId));
let options = { headers: this.headers, params: params };
return this.http.get(this.host + 'getUserById', options)
.pipe(
map((userResponse: User[]) => { // you only need to use map if you need to modify the structure of the response
return users[0]; // returns only the first user in the array that you get from the API
})
)
}
您的组件的ngOnInit()
方法应该:
user$: Observable<User>; // define this property on your component
ngOnInit(): void {
this.user$ = this.userService.getUser();
// if you need a userId for the `getUser()` then make sure
// the userId is inside your `.subscribe()` to the route params
}
您的模板应该与重构后的代码相似:
<body>
<h2>Welcome to User Page</h2>
<div class="containerUser">
<div class="items" *ngIf="(user$ | async) as user; else loading">
<h2 class="sellerUsername"><b>{{user.username}}</b></h2>
<app-user-gallery [userId]="user.userId"></app-user-gallery>
<div class="items">
<app-star-rating [userId]="user.userId"></app-star-rating></div>
</div>
</div>
<ng-template #loading>Loading...</ng-template>
</div>
</body>
推荐阅读
- javascript - “无法设置未定义的属性‘jwtClient’”尝试将 Node.js 与 Google 表格一起使用
- r - 如何将表格添加到ggplot?
- python - TypeError:添加的层必须是类Layer的实例。成立:
- python - 如何在 python 中高效地读写大型 JSON 文件?
- python - ValueError: X.shape[1] = 2 应该等于8,训练时的特征数
- rust - 尝试在 Wasm 堆中保存字符串然后将指针保存到结构中的字符串时出现“RuntimeError:内存访问越界”
- php - 我将我的 laravel 应用程序 5.6 升级到 5.8,现在当我可以尝试创建新路线时它不起作用
- python - lightgbm.Booster 中缺少方法
- nlp - 存储 NLTK 的 .similar() 的返回
- laravel - 我在使用 laravel 将多个用户 ID 发送到数据库时遇到问题