角度:属性“ then”在“可观察”类型上不存在

Alv*_*nus 0 nativescript angular

我在这里使用Nativescript来构建移动应用程序。这里有错误。在我使用Visual Studio 2017进行ASP.Net MVC 5开发中,可以使用很好$http.get().then(),但在Nativescript中则不能。

请参见下面的代码:

import { Component, OnInit } from "@angular/core";
import { HttpClient } from '@angular/common/http';

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ["./home.component.css"]
})
export class HomeComponent implements OnInit {

    constructor(private http: HttpClient) {
    }

    ngOnInit(): void {
        this.http.get('https://somewebsite.com',
            {
                params: { 'sorter': '', 'isAscending': 'true', 'searchString': '', 'currentPage': '1', 'itemsPerPage': '300' },
                headers: {
                    "Authorization": "Basic encryptedcodehere"
                }
            }).then(function (response) {
                var theData = JSON.parse(response.data);
                if (theData.Data != null && theData.Data.length > 0) {
                    log(theData.Data);
                }
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:Property 'then' does not exist on type 'Observable'.

这是怎么回事

Eug*_*ene 5

.then是Promise的方法。但是,您使用的是httpClient,它返回Observable。您应该使用.subscribe而不是.then

  ngOnInit(): void {
    this.http.get('https://somewebsite.com',
        {
            params: { 'sorter': '', 'isAscending': 'true', 'searchString': '', 'currentPage': '1', 'itemsPerPage': '300' },
            headers: {
                "Authorization": "Basic encryptedcodehere"
            }
        }).subscribe(function (data) {
            var theData = JSON.parse(data);
            if (theData.Data != null && theData.Data.length > 0) {
                log(theData.Data);
            }
        });
  }
Run Code Online (Sandbox Code Playgroud)

您可以在官方文档中阅读有关httpClientObservable的更多信息