我试图对用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});
}
答案 0 :(得分:0)
您无需实现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']);
});
答案 1 :(得分:0)
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)
);
除了轻按以外,还可以使用其他运算符进行多种组合,请花一些时间阅读更多内容。