您好,我是 Angular 和 TypeScript 的新手。我需要一个值Observable
在字符串的格式中,如何做到这一点?
BmxComponent 文件
export class BmxComponent {
asyncString = this.httpService.getDataBmx();
currentStock = this.httpService.getDataBmx2(); //this is what I want to covert to a string so I can pass it to onSubmit()
onSubmit() {
const asnNumm = this.currentStock; // passing it here changes my database, see below
this.httpService.sendData({ stock: asnNumm })
.subscribe(
data => console.log(data),
error => console.log(error)
);
}
}
HttpService 文件
export class HttpService {
constructor(private http: Http) {}
getDataBmx() {
return this.http.get('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx/stock.json')
.map((response: Response) => response.json());
}
getDataBmx2() {
return (this.http.get('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx/stock.json'));
}
sendData(newStock: any) {
const body = JSON.stringify(newStock);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.patch('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx.json', body, {
headers: headers
})
.map((data: Response) => data.json())
.catch(this.handleError);
}
private handleError(error: any) {
console.log(error);
return Observable.throw(error.json());
}
}
html 文件
<p>{{asyncString | async}}</p> // displays 1234 which is the correct value
<p>{{asyncString}}</p> // displays [object Object]
<p>{{currentStock}}</p> // displays [object Object]
<button class="btn btn-success" (click)="onSubmit()">Change Database</button>
onSubmit() 之前的我的数据库(当我单击“更改数据库”按钮时使用)
Bicycles
|
---bmx
|
---stock = 1234;
onSubmit() 之后我的数据库
Bicycles
|
--- bmx
|
---stock
|
--- _isScalar = false
我为此使用 Firebase。
我知道它可以与字符串一起使用,因为我用这样的方式测试了它:
onSubmit() {
const asnNumm = "33333" //the change to test it
this.httpService.sendData({ stock: asnNumm })
.subscribe(
data => console.log(data),
error => console.log(error)
);
}
这对我的数据库做了什么
Bicycles
|
---bmx
|
---stock = 33333
我明白那个currentStock
将保留当前存储在我的数据库中的相同值,因此它没有什么区别,但我想在将其转换为字符串后更改它。
基本上,我想更改数据库中的“库存”,但每次按“更改数据库”按钮时更改固定数量,例如,每次按下时减 1。