【问题标题】:Creating JSON Post In Angular 2在 Angular 2 中创建 JSON 帖子
【发布时间】:2016-11-25 19:08:54
【问题描述】:

我在我的 angular2 应用程序中使用 Auth0,一旦用户登录 auth0 服务,就会发送一个包含用户个人资料信息的响应。

根据用户选择的登录方法,响应可以有多种不同的方式。我只想在回复中拆分电子邮件地址。

这是一个典型的反应,

Object
clientID
:
"skdjcbjlwrjlw"
created_at
:
"2016-10-15T06:03:44.636Z"
email
:
"nick@example.com"
email_verified
:
true
family_name
:
"Walker"
gender
:
"male"
given_name
:
"Paul"
global_client_id
:
"ojwebcvjoweojewhc"
identities
:
Array[1]
locale
:
"en"
name
:
"Paul Walker"
nickname
:
"nick"
picture
:
"https://lh4.googleusercontent.com/photo.jpg"
updated_at
:
"2016-11-21T22:29:33.158Z"
user_id
:
"google-oauth2|102515181977826170152"
__proto__
:
Object

现在,当我收到该回复时,我将电子邮件地址分开,

  1. 我创建了一个类来保存电子邮件地址,

    export class User { constructor( public email: string, ) { } }

  2. 我实例化了对象,
    user: Object;

  3. 我将电子邮件从配置文件对象移动到user

this.user = profile.email;

此时的问题是我需要使用 JSON 格式的电子邮件。所以我用,

var email = JSON.stringify(this.user);

但是当我console.log(email); 我得到的是 myemail@example.com 而不是 json。

所以在这一点上,

 console.log(profile); // outputs json of whole profile
        this.user = profile.email;
        console.log(this.user); // outputs just the email address
         var email = JSON.stringify(this.user); 
        console.log(email);   // expects json gets email@example.com

我需要 email 是实际的 json。我没有正确使用JSON.stringify(this.user);

【问题讨论】:

  • 2.没有实例化任何东西。它声明了一个 Object 类型的变量。 3 将可能是字符串的 profile.email 分配给该变量。如果用户应该是用户,那么它的类型应该是用户,而不是对象。而且您不应该为该变量分配字符串。要创建 User 的实例,语法为 new User(theEmail)typescriptlang.org/docs/handbook/classes.html
  • 谢谢伙计。立即生效。我现在因为问而感到内疚。谢谢。

标签: json angular auth0


【解决方案1】:

为了提高知名度,我将 JB Nizet 的评论作为社区 wiki 答案包含在内。


第 2 步,没有实例化任何东西。它声明了一个 Object 类型的变量。

第 3 步,将profile.email(可能是一个字符串)分配给该变量。如果user 应该是User,那么它的类型应该是User,而不是Object。而且您不应该为该变量分配字符串。要创建User 的实例,语法为new User(theEmail)

查看typescriptlang.org/docs/handbook/classes.html 以供参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多