【问题标题】:Property 'then' does not exist on type 'Subscription' (Angular 9)“订阅”类型(Angular 9)上不存在属性“then”
【发布时间】: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


【解决方案1】:

您不需要实现 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']);
    
});

【讨论】:

  • 当我这样做时,它会在其他操作完成之前路由。我试图让它路由其他操作完成
  • 操作完成前无法路由。只有在执行了指定的异步操作后才会进入订阅成功块内。
  • 我指的是成功回调中的localStorageconsole.log 操作。它在运行这些函数之前路由
  • 能不能在router语句后面再写一个console语句,分享截图。
  • 什么都没有显示,没有日志只是一个`XHR加载失败:POST`错误
【解决方案2】:

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)
);

除了点击之外,还有其他几种可能的组合,请花点时间了解更多信息。

【讨论】:

  • 我仍然收到XHR failed loading: POST 错误。我想我可能有比在调用操作之前路由更深的问题。我非常感谢你们的帮助,希望我能解决这个问题或在另一篇文章中发布更深层次的问题。谢谢!
  • 哼,post 操作失败了?在您的订阅中添加错误处理,将整个错误记录到控制台。我将编辑我的答案添加它。
  • 我仍然没有在控制台中得到任何东西。我知道帖子正在通过,因为我可以看到它在终端中运行后端操作,但由于某种原因我无法在前端收到响应
猜你喜欢
  • 1970-01-01
  • 2019-01-03
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 2018-12-02
  • 1970-01-01
相关资源
最近更新 更多