尝试使用Angular创建数据时出现错误

时间:2019-10-11 18:28:33

标签: javascript angular typescript

我正在尝试使用post库中的Http方法创建新帖子。我在模板中有一个input框,如果有人通过该input框添加帖子,则该post会在列表中。

但是我在post.id=response.json().id中遇到错误。请在下面找到代码。

posts:any[];
private url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http : HttpClient) {
http.get(this.url).subscribe( (Response: any[]) => {
this.posts = Response;
} )
}
addPost(postTitle:HTMLInputElement){
let post:any = {input : postTitle.value}
postTitle.value = '';
this.http.post(this.url, JSON.stringify(post))
.subscribe( response => {
post.id = response.json().id;
this.posts.splice(0, 0, post)
//console.log( response );
})
}

3 个答案:

答案 0 :(得分:1)

错误是由json()引起的。 json()是您通常使用fetch()来解析application/json正文的方法。您不需要使用HttpClient来执行此操作,因为它会自动为您解析JSON。尝试更改:

post.id = response.json().id

只是:

post.id = response.id

更新

您表示错误Property 'id' does not exist on type 'Object'.。发生这种情况是因为您没有提供type for the response并且TypeScript不知道解析的有效负载上存在哪些属性。您可以通过以下方法解决此问题:

post.id = response['id']
// or
// post.id = (response as any).id

话虽这么说,但您应该制作一个代表有效负载结构的接口或类,并将其提供给HttpClient调用。

interface MyInterface {
  id: number;
}

// ...

this.http.post<MyInterface>(this.url, JSON.stringify(post))
  .subscribe(response => {
    post.id = response.id;
    // ...
  });

希望有帮助!

答案 1 :(得分:1)

HttpModule与旧的HttpClientModule不同,post.id = response.id向后提供json响应

因此,您可以直接设置json,因为响应已经是经过有效分析的import { Component, Input } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'hello', template: ` <input type="text" (keyup.enter)="addPost(input)" #input placeholder="Enter Post Here......." class="form-control"> <ul class="list-group mt-3"> <li class="list-group-item" *ngFor="let post of posts | slice:0:8">{{ post.title }}</li> </ul>`, styles: [`h1 { font-family: Lato; }`] }) export class HelloComponent { posts: any[]; private url = 'https://jsonplaceholder.typicode.com/posts'; constructor(private http: HttpClient) { http.get(this.url) .subscribe( (response: any[]) => { this.posts = response; }) } addPost(input: HTMLInputElement){ let post:any = { title: input.value } // since post should be an object and you are displaying post.title in the list this.http.post(this.url, JSON.stringify(post)) .subscribe( (data:any) => { console.log(data); post.id = data.id; this.posts = [post,...this.posts]; // adds the new post to the top of this.posts so that the slice(0,8) will contain the updated value }) } }

更新

请参见下面的工作代码:https://stackblitz.com/edit/angular-5tmcvj?embed=1&file=src/app/hello.component.ts

import React, { useState } from 'react';
import { Menu, Responsive, Dropdown, DropdownMenu } from 'semantic-ui-react';
import { withRouter } from 'react-router-dom';
import LogoutModal from './LogoutModal';

function NavMenu(props) {
    const [activeItem, setActiveItem] = useState('Laptop Item')
    const [showModal, setShowModal] = useState(false)


    return (
        <div>
            <Menu pointing secondary>
                <Responsive as={Menu.Item} minWidth={790}
                    name='Laptop Item'
                    active={activeItem === 'Laptop Item'}
                    onClick={() => setActiveItem('Test Item')}
                />
                <Responsive as={Menu.Item} minWidth={790}
                    name='Laptop Item 2'
                    active={activeItem === 'Laptop Item 2'}
                    onClick={() => setActiveItem('Test Item 2')}
                />
                <Responsive as={Menu.Item} minWidth={790}
                    name='Laptop Item 3'
                    active={activeItem === 'Laptop Item 3'}
                    onClick={() => setActiveItem('Test Item 3')}
                />
                <Menu.Menu position = 'right'>
                    <Responsive as ={Menu.Item} minWidth={790}
                        name = "Sign Out"
                        onClick={() => setShowModal(true)}
                    />
                </Menu.Menu>
                <Responsive as ={Menu.Menu} maxWidth={789}  position='right'>
                    <Dropdown
                        item
                        icon ='bars'
                        >
                        <Dropdown.Menu>
                            <Dropdown.Item text='Mobile/Tablet Item 1'/>
                            <Dropdown.Item text='Mobile/Tablet Item 2'/>
                            <Dropdown.Item text='Mobile/Tablet Item 3'/>
                            <Dropdown.Item text='Sign Out'/>
                        </Dropdown.Menu>
                    </Dropdown>
                </Responsive>
            </Menu>
        </div>
    )
}

export default withRouter(NavMenu);

答案 2 :(得分:0)

HttpClient始终提供json对象作为响应,因此无需使用“ .json()”方法再次解析它。 只需使用:

p = "asfdasdf"
a = [1,3,6]
output = []
for i in a:
    output.append(p[i])
print(' '.join(output))