首页 > 解决方案 > 类型上不存在属性“订阅”。甚至返回 Observable

问题描述

当我尝试订阅服务中的方法时收到编译错误,是的,我正在返回一个 Observable。

相关版本来自默认的 .net core angular 模板。

VS 代码错误

VS 代码错误。 下面是带有引用的 login.component.ts。

登录组件.ts

import { Component, OnInit } from "@angular/core";
import { LoginViewModel } from "../models/ApplicationUserViewModel";

import { LoginService } from "../services/Login.service";

@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.css"]
})
export class LoginComponent implements OnInit {
  public loginViewModel: LoginViewModel;

  constructor(private loginService: LoginService) {
    this.loginViewModel = new LoginViewModel();
  }

  ngOnInit() {}

  login(): any {
    this.loginService.login(this.loginViewModel).subscribe(
      result => {
        alert("success");
      },
      error => {
        alert("error");
      }
    );
  }
}

下面是带有引用的 login.service.ts。

登录服务.ts

import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { of } from "rxjs/observable/of";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { map } from "rxjs/operator/map";

import { LoginViewModel } from "../models/ApplicationUserViewModel";

const httpOptions = {
  headers: new HttpHeaders({ "Content-Type": "application/json" })
};

@Injectable()
export class LoginService {
  constructor(private http: HttpClient) {}

  login(loginViewModel: LoginViewModel): Observable<any> {
    return this.http.post<LoginViewModel>(
      'account/login',
      loginViewModel,
      httpOptions
    );
  }
}

谢谢你。

标签: angulartypescriptrxjs

解决方案


推荐阅读