属性'then'在类型 'Subscription' 上不存在 (角度 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)
);

使用tap以外的其他运算符可以进行多种组合,请花点时间阅读更多信息。

最新更新