gpt4 book ai didi

angularjs - Angular 2-带有 promise 返回的Http未定义

转载 作者:行者123 更新时间:2023-12-01 08:13:51 25 4
gpt4 key购买 nike

我是Angular2的新用户,我正尝试从json文件中获取数据。为此,我将Http与Promise一起使用,但是当我从promise变量中进行console.log时,它们将返回Undefined。

邮政服务

import {Injectable} from '@angular/core';
import { Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import {Post} from '../interfaces/post.interface';
@Injectable()
export class PostService{
private url = 'myjson.json';
constructor(private http: Http){ }
private extractData(res: Response) {
let body = res.json();
console.log(body.data);
return body.data || null;
}
getPosts(): Promise<Post[]>{
return this.http.get(this.url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}

posts.component.js
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {PostService} from '../services/post.service';
import {Post} from '../interfaces/post.interface';

@Component({
selector: 'posts',
template:
`
<h1>Posts</h1>
<form (submit)="addPost()">
<label for="title">Title</label>
<input type="text" [(ngModel)]="title" />
<br />
<label for="body">Body</label>
<input type="text" [(ngModel)]="body" />
<br />
<input type="submit" value="Submit" />
</form>
<ul>
<li *ngFor="let post of posts">
{{1+1}}
<h3>{{post.title}}</h3>
</li>
</ul>
`,
})

export class PostsComponent implements OnInit{
private posts:Post[];
private title:string;
private body:string;
private newPost:Object;
error: any;

constructor(private _postService:PostService){}
getPosts(){
this._postService.getPosts().then(posts => this.posts = posts).catch(error => this.error = error);
}
ngOnInit() {
this.getPosts();
console.log(this.posts);
}
addPost(){
this.newPost={
title:this.title,
body:this.body
}
}
}

post.interface.ts
    export interface Post{
id: number;
userId: number;
title:string;
body:string;
}

请有人可以帮助我吗?谢谢。

最佳答案

这是因为Promise / HTTP请求是异步的。您需要在HTTP请求的 promise 回调中添加console.log。如果您在回调之外执行此操作(即在执行请求后立即执行此操作),则响应不再存在,因此您将获得未定义的响应。

这是一个示例:

getPosts(){
this._postService.getPosts().then(posts => {
this.posts = posts;
console.log(this.posts); // not null
}).catch(error => this.error = error);
}

ngOnInit() {
this.getPosts();
console.log(this.posts); // null
}

编辑

我认为问题出在您的 extractData方法中。除非您在JSON属性中具有 body.data属性,否则不应使用 data
    private extractData(res: Response) {
let body = res.json();
console.log(body);
return body || null; // <-------
}

关于angularjs - Angular 2-带有 promise 返回的Http未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460487/

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