我正在学习Angular 4.我已经编写了服务和组件。当我调用服务时,我可以在subscribe函数中获取数据,但它不会将数据分配给类变量。这是我的服务。
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]
就像我说我是棱角分明的新手,我不知道现在究竟发生了什么。任何指导都会很棒,或者建议我做错了什么。
答案 0 :(得分:2)
由于http请求是异步的,因此未定义ngOnInit中的console.log。当触发console.log时,您的代码仍在等待来自服务器的响应,因此未定义。您可以在订阅的成功回调中看到,您有服务器数据。并且您将API结果存储在latest_works属性中。
this.latest_works = data; // response gets stored in class property
答案 1 :(得分:1)
解析器是您正在寻找的解决方案。请查看此链接https://angular.io/api/router/Resolve;说明和示例。
当您更改状态时,解析器将使用http请求调用该方法;请求完成后,路由器将更改状态,并在加载时获取html内容。