如何解决属性“ then”在“预订”类型上不存在Angular 9
我试图对用HttpClient
提取的数据执行一些操作,然后在执行这些操作后路由页面。显然,我无法使用then
来执行此操作,但是我找不到在运行这些操作后 之后如何路由页面的其他方法。否则,如果我尝试在同一功能中运行这些操作和路由,那么该页面似乎会在其他操作完成之前尝试路由。
这是我的代码:
import { Component,OnInit,ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { NbAuthSocialLink } from '@nebular/auth';
import { NbAuthService } from '@nebular/auth';
import { DataService } from '../@core/utils/data.service';
@Component({
selector: 'ngx-auth',templateUrl: './auth.component.html',styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {
constructor(
private dataService : DataService,private router : Router
){}
ngOnInit(){
}
textAnalysis(name,text){
this.dataService.sendText(text).subscribe((data: any[])=>{
console.log(data)
localStorage.setItem('user_name',name)
localStorage.setItem('insights',JSON.stringify(data));
console.log('localStorage json stringified object item set to: insights')
console.log("<----------test: should output 'Imagination'---------->")
console.log(data['personality'][0]['children'][3]['name'])
}).then(() => {
this.router.navigate(['/pages']);
})
}
}
}
和DataService
函数:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const httpOptions = {
};
declare var google: any;
@Injectable({
providedIn: 'root',})
export class DataService {
constructor(private http: HttpClient) { }
public sendText(data){
return this.http.post("//localhost:8000/personalityFromText",data,{withCredentials: true});
}
解决方法
您无需实现then块,只需将导航置于预订成功块内即可。
textAnalysis(name,text){
this.dataService.sendText(text).subscribe((data: any[])=>{
console.log(data)
localStorage.setItem('user_name',name)
localStorage.setItem('insights',JSON.stringify(data));
console.log('localStorage json stringified object item set to: insights')
console.log("<----------test: should output 'Imagination'---------->")
console.log(data['personality'][0]['children'][3]['name'])
this.router.navigate(['/pages']);
});
,
HttpClient是一个Observable,不是一个Promise,因此您将需要使用管道执行此操作,像步骤链一样思考:
this.dataService.sendText(text).pipe(
tap(data => localStorage.setItem('user_name',name)),tap(data => localStorage.setItem('insights',JSON.stringify(data))),).subscribe(
(data) => this.router.navigate(['/pages']),(error) => console.error(error)
);
除了轻按以外,还可以使用其他运算符进行多种组合,请花一些时间阅读更多内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。