練習 - 批次載入使用者的電子郵件
在這個練習中,您將延伸應用程式,讓您以 10 個為一組分批載入使用者的電子郵件。
以 10 個為一組分批載入電子郵件
從更新 getEmails()
功能開始,以 10 個為一組分批載入電子郵件。 如果已定義下一組要載入的電子郵件,它會傳遞為函數的引數。
在程式碼編輯器中,開啟 graph.js 檔案。
更新
getEmails()
函數的簽名以接受單一引數nextLink
:async function getEmails(nextLink) { // ... }
如果
nextLink
已設定,則函數應該會傳遞至 SDK 以擷取資料。 如果nextLink
尚未設定,則函數應該會載入一組初始資料。 使用下列if
陳述式取代return
陳述式以更新getEmails()
函數:if (nextLink) { return await graphClient .api(nextLink) .get(); } else { return await graphClient .api('/me/messages') .select('subject,receivedDateTime') .orderby('receivedDateTime desc') .top(10) .get(); }
更新的
getEmails()
函數看起來應該如下:async function getEmails(nextLink) { ensureScope('mail.read'); if (nextLink) { return await graphClient .api(nextLink) .get(); } else { return await graphClient .api('/me/messages') .select('subject,receivedDateTime') .orderby('receivedDateTime desc') .top(10) .get(); } }
延伸範本以允許使用者載入更多電子郵件
您擴充了 getEmails()
函數,以載入更多電子郵件。 下一個步驟是顯示按鈕,讓使用者載入更多電子郵件(如果可用)。
在程式碼編輯器中,開啟 index.html 檔案。
找到行
<ul id="emails"></ul>
,並在它之後緊接著加入下列程式碼,以新增可讓使用者載入更多電子郵件的按鈕。<div id="loadMoreContainer" style="display: none;"> <button onclick="displayEmail();">Load more</button> </div>
載入更多電子郵件
更新應用程式以讓使用者載入更多電子郵件,最後一個步驟是新增功能以處理載入更多電子郵件。
在程式碼編輯器中,開啟 ui.js 檔案。
在
displayEmail()
函數之前,請定義名為nextLink
的新變數,但不要指派值給該變數:var nextLink;
在
displayEmail()
函數中,更新呼叫以取得getEmails()
函數以包含nextLink
。var emails = await getEmails(nextLink);
接下來,在擷取資料之後,取得
@odata.nextLink
屬性的值。 一旦設定,則會表示有更多可提供使用者的資料可顯示。 在displayEmail()
函數中的if
陳述式後面緊接著新增下列程式碼:nextLink = emails['@odata.nextLink'];
在
displayEmail()
函數的結尾,顯示已擷取的電子郵件後,捲動至頁面結尾,讓使用者可以立即看到所擷取的電子郵件。window.scrollTo({ top: emailsUl.scrollHeight, behavior: 'smooth' });
最後,檢查
nextLink
是否已返回,如果是,則顯示按鈕以載入更多電子郵件。將下列程式碼新增至
displayEmail()
函數的結尾:if (nextLink) { document.getElementById('loadMoreContainer').style = 'display: block'; }
完整的
displayEmail()
函數看起來應該如下:var nextLink; async function displayEmail() { var emails = await getEmails(nextLink); if (!emails || emails.value.length < 1) { return; } nextLink = emails['@odata.nextLink']; document.getElementById('displayEmail').style = 'display: none'; var emailsUl = document.getElementById('emails'); emails.value.forEach(email => { var emailLi = document.createElement('li'); emailLi.innerText = `${email.subject} (${new Date(email.receivedDateTime).toLocaleString()})`; emailsUl.appendChild(emailLi); }); window.scrollTo({ top: emailsUl.scrollHeight, behavior: 'smooth' }); if (nextLink) { document.getElementById('loadMoreContainer').style = 'display: block'; } }
執行您的應用程式
您利用 Microsoft Graph 分批使用 10 個為一組的項目,擴充您的應用程式以顯示使用者的電子郵件,並讓他們載入更多電子郵件。 讓我們在本機執行應用程式。
在終端機中執行下列命令來預覽 Web 應用程式。
npm start
您的瀏覽器應該會指向
http://localhost:8080
。選取 [使用 Microsoft 帳戶登入] 按鈕以使用您的 Microsoft 365 帳戶登入。
使用帳戶登入之後,選取 [顯示電子郵件] 按鈕。
您應該會看到應用程式中顯示的使用者最後 10 封電子郵件清單。
如果您的信箱中超過 10 封電子郵件,則會看到一個按鈕,可讓您載入下一批次的 10 封郵件。
在終端機視窗中選取 CTRL+C 以停止 Node.js 伺服器。