Angular 订阅服务中的变量时出现问题
我正在学习Angular并尝试侦听一个包含http请求值的变量。这是服务Angular 订阅服务中的变量时出现问题,angular,rxjs,httprequest,listener,rxjs6,Angular,Rxjs,Httprequest,Listener,Rxjs6,我正在学习Angular并尝试侦听一个包含http请求值的变量。这是服务 export class UsersService { message = new Subject<string>(); constructor(private http: HttpClient) { } addUser(userData: {username, email, password, school}) { this.http.post<any>('http://127.0.0
export class UsersService {
message = new Subject<string>();
constructor(private http: HttpClient) { }
addUser(userData: {username, email, password, school}) {
this.http.post<any>('http://127.0.0.1/apiapp/insert.php', userData).subscribe( (r) => {
this.message = r.message;
});
}
我得到一个空白的数据,没有任何记录,只是控制台中的一个空白行。这是为什么?如何解决?
提前感谢您这里有3个问题 您没有通过主题正确发送值 您的console.logthis.result的位置存在一些异步问题 您需要调用.asObservable对您的主题进行观察,以使主题成为可观察的
export class UsersService {
message = new Subject<string>();
constructor(private http: HttpClient) { }
addUser(userData: {username, email, password, school}) {
this.http.post<any>('http://127.0.0.1/apiapp/insert.php', userData).subscribe( (r) => {
// .next is how you send data via a subject
this.message.next(r.message);
});
}
result = '';
private resultSubscription: Subscription;
ngOnInit() {
// Get subject as observable
this.resultSubscription = this.userS.message.asObservable().subscribe( (r) => {
this.result = r;
// by logging here we can ensure that the result will be populated
console.log(this.result);
});
}
addPost(userData: {username: string, email: string, password: string, school: string}) {
this.userS.addUser(userData);
}
// It is important to unsubscribe for your observable when the component is destroyed
ngOnDestroy(): void { this.resultSubscription.unsubscribe(); }
Ngondestory:void{this.resultSubscription.unsubscribe;}在这种情况下,这对于防止内存泄漏很重要,对吗?@PHPUser你是对的,完全忘记了这一点。我的道歉
export class UsersService {
message = new Subject<string>();
constructor(private http: HttpClient) { }
addUser(userData: {username, email, password, school}) {
this.http.post<any>('http://127.0.0.1/apiapp/insert.php', userData).subscribe( (r) => {
// .next is how you send data via a subject
this.message.next(r.message);
});
}
result = '';
private resultSubscription: Subscription;
ngOnInit() {
// Get subject as observable
this.resultSubscription = this.userS.message.asObservable().subscribe( (r) => {
this.result = r;
// by logging here we can ensure that the result will be populated
console.log(this.result);
});
}
addPost(userData: {username: string, email: string, password: string, school: string}) {
this.userS.addUser(userData);
}
// It is important to unsubscribe for your observable when the component is destroyed
ngOnDestroy(): void { this.resultSubscription.unsubscribe(); }