![](/img/trans.png)
[英]Angular 2 Property subscribe does not exist on type Promise <any>
[英]Subscribe' does not exist on type 'Promise<User>' Angular 6
从4号角到6号角代码,现在我在vs代码中遇到错误,说类型'Promise'不存在属性'subscribe'。 错误在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)
}
}
错误消息自我解释。 您正在尝试访问Promise
subscribe
功能,该功能不可用。
您应该使用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编辑器中编写的。 可能有拼写错误或语法错误。 请纠正自己。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.