我的Angular和Typescript代码出了什么问题?

问题描述 投票:1回答:2

我正在尝试从API获取数据并将其绑定到我的“标题”属性,如下面的代码所示。但是我在“回调”函数中写的是:this.headline = res;

不起作用,标题不受约束。但是,如果我在fetchData方法中放入相同的代码,它就可以了!但对我来说似乎没有什么区别?我是打字稿的新手,我在这里做错了什么?

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

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})

export class HomeComponent {
    public news: News[];
    public headline: News;
    constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {

    }
    ngOnInit() {
        var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
        this.fetchData(headurl, function (res) {
            //this code does not work
            this.headline = res;
        });

    }

    fetchData(url, callback) {
        this.http.get<News>(url).subscribe(result => {
            callback(result);
            //this code works!
            this.headline = result;
        }, error => console.error(error));

    }
}


interface News {
    SourceId: string;
    SourceName: string;
    Author: string;
    Title: string;
    Description: string;
    Url: string;
    UrlToImage: string;
    PublishedAt: string;
}
angular typescript angular-httpclient
2个回答
1
投票

您需要使用箭头函数,以便在回调发生时捕获this

ngOnInit() {
    var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
    this.fetchData(headurl, (res) => {
        this.headline = res;
    });
}

更好的设计是将Observable返回给调用者,而不是将回调传递给被调用的方法,让调用者决定如何处理结果。

ngOnInit() {
    var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
    this.fetchData(headurl).subscribe((res) => {
        this.headline = res;
    });
}

fetchData(url) : Observable<News> {
    return this.http.get<News>(url);
}

1
投票

箭头函数从声明上下文中捕获this而常规函数没有并且this依赖于调用者(基本上调用者决定将this发送给函数)

使用noImplicitThisstrict(尽管严格打开更多选项)编译器选项以避免此类错误。

要解决此特定问题,还可以使用箭头函数进行第一次调用:

ngOnInit() {
    var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
    this.fetchData(headurl, (res) => {

        this.headline = res;
    });

}
© www.soinside.com 2019 - 2024. All rights reserved.