简体   繁体   English

如何在Angular中将对象转换为JSON

[英]How to convert an object to JSON in Angular

Found some answers for angularjs like: How to use angular.toJson on a angular controller or scope but not Angular 2 and following. 找到了一些有关angularjs的答案,例如: 如何在angular控制器或示波器上使用angular.toJson,但在Angular 2及更高版本中不使用。

I'm new to Angular, worked through the tutorial, and now trying to build my first live app. 我是Angular的新手,已完成本教程的学习,现在尝试构建我的第一个实时应用程序。 I have a credentials object that has fields username and password. 我有一个包含字段用户名和密码的凭据对象。 I want to externalize this to JSON to send to my web service. 我想将其外部化为JSON以发送到我的Web服务。 I found this: https://angular.io/api/common/JsonPipe which seems to do what I want, but the example is in HTML and I want to do it in my service, so here's my service: 我发现了这一点: https : //angular.io/api/common/JsonPipe似乎可以满足我的要求,但是示例在HTML中,并且我想在我的服务中执行,因此这是我的服务:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class LoginService {
  authToken = ""
  loginUrl = "localhost:8093/login"

  constructor(private http: HttpClient) { }

  login(credentials): Observable<String> {
    var url = this.loginUrl
                + '?payload='
                + (credentials | json)
    return of(url);
  }
}

But I get an error on the line + (credentials | json) saying json is not found, maybe I meant JSON? 但是我在+ (credentials | json)行上收到一条错误消息,说找不到json,也许我的意思是JSON?

Did I? 是吗

Just use 只需使用

JSON.stringify(credentials)

like in plain JavaScript. 就像纯JavaScript一样。

The | json | json | json pipe is only for view binding like | json管道仅用于视图绑定,例如

{{credentials | json}}

but not for TypeScript code. 但不适用于TypeScript代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM