我正在尝试将网页上文本框字段中写入的项目传递给组件文件中的变量。这些变量然后将在服务文件中使用,该文件具有功能链接到我在python / SQLAlchemy端发出的POST请求。我在后端和Angular CLI 7.0.5中将Flask与python / SQLAlchemy一起使用。这是我所拥有的:
<div class = "container">
<input id="InsertItemName" [(ngModel)]="InsertItemName"/>
<input id="InsertItemManu" [(ngModel)]="InsertItemManu"/>
<input id="InsertItemType" [(ngModel)]="InsertItemType"/>
<button (click)="sendValues()">Send</button>
</div>
modify-page.component.html:
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Data } from '@angular/router';
import { HttpResponse } from '@angular/common/http';
import { SelectItem } from 'primeng/components/common/selectitem';
import { MenuItem } from 'primeng/api';
import { ModifyService, ItemsData } from '../modify.service'
import { PARAMETERS } from '@angular/core/src/util/decorators';
@Component({
selector: 'app-modify-page',
templateUrl: './modify-page.component.html',
styleUrls: ['./modify-page.component.css']
})
export class ModifyPageComponent implements OnInit {
InsertItemName: string;
InsertItemManu: string;
InsertItemType: string;
insertItems: ItemsData;
constructor(
private modifyService: ModifyService,
private route: ActivatedRoute
) {
}
ngOnInit() {
this.insertItems.name = this.InsertItemName;
this.insertItems.manufacture = this.InsertItemManu;
this.insertItems.type = this.InsertItemType;
}
sendValues(): void {
console.log(this.InsertItemName, this.InsertItemManu, this.InsertItemType)
this.modifyService.postInputItems(this.insertItems)
}
}
modify.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export interface ItemsData {
name: string;
manufacture: string;
type: string;
}
@Injectable({
providedIn: 'root'
})
export class ModifyService {
constructor(
public http: HttpClient
) { }
postInputItems(data: ItemsData){
return this.http.post('/modify/insertItems', data)
}
}
如果需要的话,这就是database.py:
def insert_dbItems(a, b, c):
with engine.connect() as con:
ins = Items.insert().values(name = a, manufacture = b, type = c)
con.execute(ins)
return "Successfully inserted data into Items table"
和 init .py:
@app.route('/api/modify/insertItems', methods=["POST"])
def insert_Itemsdb():
body = json.loads(request.data)
a = body['name']
b = body['manufacture']
c = body['type']
return jsonify(database.insert_dbItems(a, b, c))
数据库和init文件可以正常工作,我可以使用Postman应用程序并将其正确地从数据库中插入变量。我的问题是,当我运行上面的所有代码时,都会得到以下提示:
最后:对于我来说,这里的一切都是要接受用户的输入并将其插入到我的数据库中。任何帮助都将非常棒,谢谢!
答案 0 :(得分:0)
我认为您忘记了在ModifyPageComponent顶部初始化insertItems。
insertItems: ItemsData = {
name: null;
manufacture: null;
type: null;
}
希望会有所帮助!