2016-11-21 56 views
0

我在我的angular2應用程序中使用Auth0,一旦用戶登錄auth0服務,發送一個響應來保存用戶配置文件信息。在Angular 2中創建JSON發佈

根據用戶選擇的登錄方法,響應可以有多種不同的方式。我只想分開回復中的電子郵件地址。

這是一個典型的反應,

Object 
clientID 
: 
"skdjcbjlwrjlw" 
created_at 
: 
"2016-10-15T06:03:44.636Z" 
email 
: 
"[email protected]" 
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. 我實例化t他反對,
    user: Object;

  3. 我移動電子郵件從配置文件對象到user

this.user = profile.email;

的問題在這一點上我需要的電子郵件是JSON格式。所以我用,

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

但是,當我console.log(email); 我得到[email protected]而不是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 protected] 

我需要的email是實際的JSON。我沒有正確使用JSON.stringify(this.user);嗎?

+0

2.沒有實例化任何東西。它聲明瞭一個Object類型的變量。 3給該變量分配profile.email,可能是一個字符串。如果用戶應該是一個用戶,它的類型應該是User,而不是Object。而且你不應該爲該變量分配一個字符串。要創建用戶的實例,語法是'new User(theEmail)'。 https://www.typescriptlang.org/docs/handbook/classes。html –

+0

謝謝你。立即工作。我現在因爲提問而感到內疚。謝謝。 – wuno

回答

0

爲了獲得更好的可見性,我將包含來自JB Nizet的評論作爲社區維基答案。


步驟2,沒有任何實例。它聲明瞭一個Object類型的變量。

步驟3,分配profile.email,這可能是一個字符串,該變量。如果user應該是User,則其類型應爲User,而不是Object。而且你不應該爲該變量分配一個字符串。要創建User的實例,語法是new User(theEmail)

查詢typescriptlang.org/docs/handbook/classes.html僅供參考。