json 如何在打字稿中将存储在 Observable<any> 中的值转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42554366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:48:34  来源:igfitidea点击:

How to convert the value stored in Observable<any> to a string, in typescript?

jsonstringangulartypescriptobservable

提问by questions

Hi I am new to Angular and TypeScript. I need the value of an Observablein the format of a string, how does one do this?

嗨,我是 Angular 和 TypeScript 的新手。我需要Observable一个字符串格式的值,如何做到这一点?

the BmxComponent file

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)
            );
    }
}

the HttpService file

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());
    }
}

the html file

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>

my database before onSubmit() (used when I click the Change Database button)

我在 onSubmit() 之前的数据库(当我单击“更改数据库”按钮时使用)

Bicycles
|
---bmx
    |
    ---stock = 1234;

my database after onSubmit()

onSubmit() 之后我的数据库

Bicycles
|
--- bmx
     |
     ---stock
         |
         --- _isScalar = false

I am using Firebase for this.

我正在为此使用 Firebase。

I know it will work with a string because I tested it with like this:

我知道它可以与字符串一起使用,因为我是这样测试的:

    onSubmit() {
        const asnNumm = "33333" //the change to test it
        this.httpService.sendData({ stock: asnNumm })
            .subscribe(
            data => console.log(data),
            error => console.log(error)
            );
    }

Which does this to my database

这对我的数据库执行此操作

Bicycles
|
---bmx
    |
    ---stock = 33333

I understand that currentStockwould hold the same value that is currently stored in my database, so it would make no difference, but I want to change it once I have converted it to a string.

我知道这currentStock将保存当前存储在我的数据库中的相同值,因此它没有区别,但是一旦将其转换为字符串,我想更改它。

Basically I want to change "stock" in my database, but by a fixed amount each time I press the Change Database button, for example, minus 1 it each time it is pressed.

基本上我想更改我的数据库中的“库存”,但是每次按下更改数据库按钮时更改固定数量,例如,每次按下时减 1。

回答by Günter Z?chbauer

Subscribe to the observable to get the result and call onSubmitwhen you receive the value:

订阅 observable 获取结果并onSubmit在收到值时调用:

currentStock = this.httpService.getDataBmx2()
.subscribe(val => this.onSubmit(val));

回答by Roman C

Objects has toStringmethod that you can implement to show the value of object, or convert it to string with JSON.stringify()like this

对象具有toString您可以实现的方法来显示对象的值,或者JSON.stringify()像这样将其转换为字符串

this.httpService.sendData({ stock: asnNumm })
        .subscribe(
        data => console.log(JSON.stringify(data)),
        error => console.log(error)
        );

You have to map to the response object to get data, to get data as text you can query response object

您必须映射到响应对象才能获取数据,要将数据作为文本获取,您可以查询响应对象

getDataBmx2() {
    return this.http.get('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx/stock.json')
        .map((response: Response) => response.text());
}


export class BmxComponent {
    currentStock: string;

   this.httpService.getDataBmx2().subscribe(s => this.currentStock = s); //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