Я пытаюсь добавить несколько вложений в элемент списка SharePoint. Метод службы принимает список вложений и должен возвращать ответ только после загрузки всех файлов (Sharepoint API принимает только один файл за раз). Поэтому для этой цели я использую rxjs forkJoin.
Ниже приведен класс обслуживания, который я написал.
import { Injectable } from '@angular/core';
import { Observable, forkJoin } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { ContextService } from './context.service'
import { mergeMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AttachmentService {
constructor(private httpClient: HttpClient) { }
addAttachmentsToTheList(listName: string, listItemId: number, attachmentList: any[], diagest: any) {
//get the file upload observable list
let fileUploadOnservables: any[] = [];
attachmentList.forEach(file => {
fileUploadOnservables.push(this.addAttachment(listName, listItemId, file, diagest))
});
// use forkJoin to combine the operations and subscribe to all results
// use forkJoin to combine the operations and subscribe to all results
forkJoin(fileUploadOnservables)
.subscribe(
(response) => {
//after all the successful requests do something
}
);
}
}
//this will add a single attachment to list
addAttachment(listName: string, listItemId: number, file: any, diagest: any) {
//first read the file as buffer, and pass the buffer to the Sharepoint REST API
return this.getFileBuffer(file)
.pipe(
mergeMap((fileBuffer: any) => {
//once file buffer observable returns pass the buffer to the Sharepoint REST API
return this.httpClient.post(
"../_api/lists/GetByTitle('" + listName + "')/items(" + listItemId + ")/AttachmentFiles/add(FileName='" + file.name + "')",
fileBuffer,
{
headers: new HttpHeaders({
'X-RequestDigest': diagest,
'Accept': 'application/json; odata=verbose',
'Content-Type': 'application/json; odata=verbose'
})
})
})
);
}
//this returns the file buffer
getFileBuffer(file) {
return new Observable(subscriber => {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (e: any) {
subscriber.next(e.target.result);
subscriber.complete();
};
});
}
}
В компоненте:
someMethod(){
this.attachmentService.addAttachmentsToTheList('SomeList', 1, this.attachmentList,diagest)
.subscribe(
(result: any) => {
//do something
},
(error: any) => {
//handle error
});
}
Этот код выдает ошибку ниже, но также загружает файл. Что я делаю не так, как исправить эту ошибку?
Cannot read property 'subscribe' of undefined
Ценю вашу помощь.
addAttachmentsToTheList
или в компоненте, вызывающем службу? - person tnc1997   schedule 12.12.2020