gpt4 book ai didi

javascript - Angular 4变量在订阅外未定义

转载 作者:行者123 更新时间:2023-11-30 11:30:13 25 4
gpt4 key购买 nike

我正在学习 Angular 4。我已经编写了服务和组件。当我调用该服务时,我可以在订阅函数中获取数据,但它不会将数据分配给类变量。这是我的服务。

import { Injectable } from "@angular/core";
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import { Work } from '../shared/work'

import { API } from './../utils/api.data'

@Injectable()
export class WorkService {
public api: API = new API();
private api_url: string = this.api.url+'works/latest/2/';
constructor(
private http: Http
){

}

public getLatestWorks(): Observable<Work[]>{
return this.http.get(this.api_url)
.map((response:Response) => <Work[]>response.json()['data']);

}
}

这是组件

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { WorkService } from './../work.service/work.service';
import { Work } from './../shared/work';

@Component({
selector: 'latest_works',
templateUrl: './latest.works.component.html',
providers: [ WorkService ]
})
export class LatestWorksComponent implements OnInit {
public latest_works: Work[];
public errorMessage: string;

constructor(
private workService: WorkService
){}

private getLatestWorks(){
this.workService.getLatestWorks()
.subscribe(
data => {
this.latest_works = data
console.log('data inside the subscribe ' + data);
console.log('latest_works inside the subscribe ' + this.latest_works);
},
error => this.errorMessage = <any>error
);

}

ngOnInit(){
//console.log(this.latestworks());
this.getLatestWorks();
console.log('data ' + this.latest_works);
}

}

这是类的输出。

[Log] data undefined
[Log] Angular is running in the development mode. Call enableProdMode() to enable the production mode.
[Log] data inside the subscribe [object Object],[object Object]
[Log] latest_works inside the subscribe [object Object],[object Object]

就像我说的,我是 Angular 的新手,我不知道现在到底发生了什么。任何指导都会很棒,或者任何我做错的建议。

最佳答案

你在 ngOnInit 中的 console.log 是未定义的,因为 http 请求是异步的。当 console.log 被触发时,您的代码仍在等待来自服务器的响应,因此是未定义的。您可以在订阅的成功回调中看到,您拥有服务器数据。您将 API 结果存储在 latest_works 属性中。

this.latest_works = data; // response gets stored in class property

关于javascript - Angular 4变量在订阅外未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com