【发布时间】:2020-09-06 17:35:36
【问题描述】:
我正在尝试对使用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});
}
【问题讨论】:
-
订阅一个 observable 给你一个订阅,而不是一个承诺。为什么该行不能在订阅回调中?
-
你能告诉我你的意思吗?
-
编译器告诉你我的意思,这就是“属性 'then' 在类型 'Subscription'l 上不存在的意思;它不是一个承诺。跨度>
-
你在哪里调用
textAnalysis()函数?您是否希望在路由之前等待此功能完成?
标签: angular httpclient angular8 angular9