【问题标题】:Subscribe' does not exist on type 'Promise<User>' Angular 6'Promise<User>' Angular 6 类型上不存在订阅'
【发布时间】:2018-12-08 07:43:41
【问题描述】:

从 angular 4 到 angular 6 代码现在我在 vs 代码中遇到错误,说属性 'subscribe' 在类型 'Promise' 上不存在。错误在 Profile.component.ts 中。不知道是什么问题

下面是代码

用户类

export class User {
   id: number
   name: string
   email: string
   avatar: string
   joined: string
}

用户服务

import { Injectable } from '@angular/core'
import { AuthService } from './auth.service'
import { Http, Headers, RequestOptions } from '@angular/http';
import { CONFIG } from '../config/config'
import { User } from '../classes/User'
import 'rxjs'


    @Injectable()

    export class UserService {
        private headers: Headers
        constructor(private authService: AuthService, private http: Http) {
            this.headers = new Headers({ 'Authorization': `Bearer ${this.authService.getToken()}` })
        }

        getUserById(id: number): Promise<User> {
            if (id == this.authService.getAuthUserId()) {
                return Promise.resolve(this.authService.getAuthUser())
            }

            let options = new RequestOptions({ headers: this.headers })
            this.http.get(`${CONFIG.API_URL}/user/${id}`, options)
                .subscribe((response) => {
                    console.log(response.json())
                })
        }
    }

配置文件组件.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'
import { UserService } from '../services/user.service'
import { User } from '../classes/User'

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  id: number
  user: User
  constructor(private router: ActivatedRoute, private userService: UserService) { }

  ngOnInit() {
    this.router.params.subscribe((param) => {
      this.id = +param['id']
    })

    this.userService.getUserById(this.id)
      .subscribe((user) => this.user = user)
  }

}

【问题讨论】:

    标签: javascript angular angular6


    【解决方案1】:

    错误信息一目了然。您正在尝试访问不可用的Promisesubscribe 功能。

    您应该使用then 而不是subscribe

      this.userService.getUserById(this.id)
          .then((user) => this.user = user)
      }
    

    注意:您可能还需要更改getUserById 的实现。因为它看起来不正确。

    getUserById(id: number): Promise<any> {
                const p = new Promise<string>((resolve, reject) =>  {
                if (id == this.authService.getAuthUserId()) {
                    return resolve(this.authService.getAuthUser())
                }
                let options = new RequestOptions({ headers: this.headers })
                this.http.get(`${CONFIG.API_URL}/user/${id}`, options)
                    .subscribe((response) => {
                        resolve(response.json())
                    })
    
          });
          return p;
    
      }
    

    注意:由于代码是直接在 stackoverflow 编辑器中编写的。可能存在拼写错误或语法错误。请改正。

    【讨论】:

    • 如果将其更改为 "then" ,它什么也不说,但在控制台中显示错误。通过安慰 TypeError: Cannot read property 'then' of undefined at Profile.component.ts 。
    • 检查getUserById函数变化的答案。
    • 下面发生在“return p” 类型“Promise”不可分配给类型“Promise”。类型“字符串”不可分配给类型“用户”。
    • Promise&lt;User&gt; 更改为Promise&lt;any&gt;
    • 谢谢先生。它起作用了:-)你能解释一下确切的错误是什么吗?
    猜你喜欢
    • 2018-11-30
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2019-01-03
    • 1970-01-01
    • 2018-01-29
    • 2018-02-01
    相关资源
    最近更新 更多