【发布时间】:2021-09-30 20:08:12
【问题描述】:
我是 Angular 新手,我正在尝试从我的 Angular 应用程序调用 Microsoft Graph API 以显示来自 Microsoft 帐户的个人资料照片。身份验证过程使用 Azure AD 执行。
环境.ts
azure: {
tenantId: "xxxxxxxxxxxxxxxxxxxxxx",
applicationId: "xxxxxxxxxxxxxxxxxxx",
endpoint: {
root: 'https://graph.microsoft.com/v1.0',
profile: '/me',
profilePhoto: '/me/photo'
},
redirectUri: 'http://localhost:4200'
}
我开发了一个代码来验证从 API 获取个人资料照片。下面是我的
profile.component.ts
get_profile_photo() {
this.msg.getProfilePhoto().subscribe(
(response) => {
console.log('get_profile_photo() success');
console.log(response);
this.profilePhoto = response;
},
(error) => {
console.error("Error getting MS Graph Profile \n" + JSON.stringify(error));
throw (error);
}
)
}
这将调用
ms-graph.service.ts
getProfilePhoto() {
return this.httpClient.get<ProfilePhoto>(
env.azure.endpoint.root+'/me/photo'
);
}
然后我得到如下成功响应
{@odata.context: "https://graph.microsoft.com/v1.0/$metadata#users('…a69c7-94ad-49ad-8d5d-xxxxxxxxxxxx')/photo/$entity", @odata.mediaContentType: "图片/jpeg", @odata.mediaEtag: "W/"94777476813e1400e64bca040592df3b92f1ec7c2baxxxxxxxxxxxxxxx"", id: "648x648", height: 648, ...}
但这需要在将 URL 传递给 src="" 属性之前转换为 base64。 我参考了网上的许多教程,但无法转换。
然后我尝试了以下方法,使用上述身份验证从 MS 帐户获取个人资料照片。
ms-graph.service.ts
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, {responseType: 'blob'})
.map((res: Response) => res.blob);
}
第二个选项我的 ts 代码是这样的
profile.component.ts
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
console.log(this.imageToShow);
return this.imageToShow;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
get_profile_photo() {
this.isImageLoading = true;
this.imageService.getImage('https://graph.microsoft.com/v1.0/me/photo').subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
})
}
然后我得到了以下错误。
core.js:6479 ERROR TypeError: Cannot read property 'get' of undefined
at ImageService.getImage (image.service.ts:12)
at ProfileComponent.get_profile_photo (profile.component.ts:65)
at ProfileComponent_Template_button_click_23_listener (profile.component.html:15)
at executeListenerWithErrorHandling (core.js:15308)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:15346)
at HTMLButtonElement.<anonymous> (platform-browser.js:560)
at ZoneDelegate.invokeTask (zone.js:406)
at Object.onInvokeTask (core.js:28659)
at ZoneDelegate.invokeTask (zone.js:405)
at Zone.runTask (zone.js:178)
谁能帮我解决这个问题并从 MS 帐户获取个人资料照片?
【问题讨论】: