I receive an array of URLs from JSON request
This my code
if let slideShow = self.json["graphql"]["shortcode_media"]["edge_sidecar_to_children"]["edges"][].array {
for allMedia in slideShow {
let medias = allMedia["node"]["display_resources"][2]["src"].stringValue
print("All Media \(medias)")
}
}
I want to show the user a preview of every image, so I need each of these URLs individually. How I can get a single URL from this array?
You just need to create var array of strings, then append a new url string to it inside for loop:
var medias = [String]()
if let slideShow = self.json["graphql"]["shortcode_media"]["edge_sidecar_to_children"]["edges"][].array {
for allMedia in slideShow {
medias.append(allMedia["node"]["display_resources"][2]["src"].stringValue)
}
print("All Media \(medias)")
}
Related
I have a problem of uploading image to image column in sharepoint online via pnpjs
I don't know how to convert image and upload to image column in sharepoint list.
I tried lot of ways (by convert image to blob, filedata) nothing works.
Keep in much this is not an attachments for the list..
It's a new column(image) in sharepoint list
reference image click here
Looks like the image is not stored in the list. JSON is stored. So you can just upload image to site assets (that's what sharepoint does when you set the image manually) and then put the json to the field. I would try something like this (assuming you are using pnpjs)
import * as React from "react";
import { sp } from "#pnp/sp/presets/all";
// hello world react component
export const HelloWorld = () => {
const uploadFile = async (evt) => {
const file: File = evt.target.files[0];
// upload to the root folder of site assets in this demo
const assets = await sp.web.lists.ensureSiteAssetsLibrary();
const fileItem = await assets.rootFolder.files.add(file.name, file, true);
// bare minimum; probably you'll want other properties as well
const img = {
"serverRelativeUrl": fileItem.data.ServerRelativeUrl,
};
// create the item, stringify json for image column
await sp.web.lists.getByTitle("YourListWithImageColumn").items.add({
Title: "Hello",
YourImageColumn: JSON.stringify(img)
});
};
return (<div>
<input type='file' onChange={uploadFile} />
</div>);
};
#azarmfa,
The image file in fact did not store in the image field. The field just references its location. You could first upload the image file to a library (by default it will be site asset), then update the item like below:
let list = sp.web.lists.getByTitle("mylinks");
let json = {
"fileName": "Search_Arrow.jpg",
"serverUrl": "https://abc.sharepoint.com",
"serverRelativeUrl": "/sites/s01/Style%20Library/Images/Search_Arrow.jpg"
};
let jsonstr = JSON.stringify(json);
const i = await list.items.getById(3).update({
Title: "My New Tit",
img: jsonstr
});
BR
i have a firebase database as follows:
I wish to retrieve the information of this JSON on my page single address but I do not know how to do it to do it because I am new in angular and firebase. below my different codes
Adress list html
<ion-card *ngFor="let item of items;" (click)="editItem(item.key)">
<div><b>{{item.prenom}} {{item.nom}}</b></div>
</ion-card>
Address list .ts (method)
editItem(key){
const UserId = firebase.auth().currentUser.uid;
var usersRef = firebase.database().ref('adresse');
var adaRef = usersRef.child(UserId);
var adaFirstNameRef = adaRef.child(key);
var path = adaFirstNameRef.toString();
console.log(path);
this.router.navigate(['single-adresse/' +key]);
}
how to get the data on the unique address page. if you have examples I'm interested
I can recover the JSON link from firebase thanks to the child.
You can fetch data from firebase like this
Ref : https://firebase.google.com/docs/database/web/read-and-write
var usersRef = firebase.database().ref('adresse/'+UserId);
usersRef.once('value').then(snapshot=>{
let data = snapshot.val()
console.log(data);
// add your login here
})
In reactjs, I am trying to store the id to session storage array which comes from URL, for example, http://localhost:3000/#/carnivallist/171 what's the solution to store all the ids?
I can only store one id. when the page refreshes the id is getting replaced on the session storage.
componentDidMount() {
if(this.props.params.id) {
let pro_id=[this.props.params.id];
console.log(pro_id);
console.log("otem");
let items=sessionStorage.getItem("carnival_dones");
console.log(items);
if(items!=""){
this.setState({ carnival_done: [...this.state.carnival_done,{carnival_done:pro_id}]});
}else{
this.setState({carnival_done:pro_id});
}
}
}
I expect to get all ids in an array but the session storage stores only the last value get saved. and the value not accessible through the session get method
You would have to save an array, something like below code:
let items = JSON.parse(sessionStorage.getItem("carnival_dones"));
if(!items){
items = []
}
items.push(this.state.carnival_done)
sessionStorage.setItem("carnival_dones",items);
Try saving array as json and parse it when retrieving.
componentDidMount()
{
if(this.props.params.id)
{
let pro_id = this.props.params.id;
let items = JSON.parse(sessionStorage.getItem("carnival_dones"));
if(items)
{
this.setState({ carnival_done: [...this.state.carnival_done, pro_id]});
}
else
{
this.setState({carnival_done: [pro_id]});
}
}
}
// Save session
save = () =>
{
sessionStorage.setItem("carnival_dones", JSON.parse(this.state.carnival_done));
}
The problem was I was using the
componentDidMount method instead of using componentWillMount so I found a solution changing the hook
componentWillMount() {
if(this.props.params.id) {
let pro_id=[this.props.params.id];
console.log(pro_id);
console.log("otem");
let items=sessionStorage.getItem("carnival_dones");
console.log(items);
if(items!=null){
this.setState({carnival_done:[...this.state.carnival_done,[items,pro_id]]});
//this.setState({ carnival_done: [...this.state.carnival_done,pro_id]});
console.log(this.state.carnival_done);
}else{
this.setState({carnival_done:[pro_id]});
}
}
}
Thank you so much for your support
What I'm working with
angular2
firebase
What I have
A returned object
Each item in the object has a URL property
What I would like to do
Loop through each of the items in the object and get the URL property
Pass that into a firebase storage variable
Push the URL property into an array to make available for my HTML
note: I have this working by hard coding a url, I just need some assistance looping through the object to get the other urls in the object.
Component.ts
'this.imagesToDisplay' will return an object of object (image below)
this.activatedRoute.data
.subscribe((
data: { issueData: any, issueImageData: any }) => {
this.issueToDisplay = data.issueData;
this.imagesToDisplay = data.issueImageData;
this.testing(this.imageToDisplayArray);
});
Comnponent TS - Testing method
So this is hardcoded and pushes the hardcoded url into the array and displays correctly through databinding with the HTML. Cool. However, I would like to loop through the 'imagesToDisplay' object and get both returned urls.
testing(imageToDisplayArray) {
// this works with one url
var storage = firebase.storage().ref().child("image/-Kosd82P-bmh4SFetuf3/-Kosd8HhGmFiUhYMrlvw/30DD9F39-4684-4AA0-9DBF-3B0F0C3450A4.jpg");
storage.getDownloadURL().then(function(url) {
imageToDisplayArray.push(url);
console.log(imageToDisplayArray);
});
}
Any help here would be massively appreciated.
Note: I think this question here is what I'm trying to do, I'm just not sure how to integrate that into my current code. Any help would be awesome.
Stack Overflow question on firebase storage looping
UPDATE
So, I'm incredibly close now. I just have one issue. The code below loops through the returned data and extract the URL properties. I use the url properties to connect to the firebase storage and return the download URLs. Both of these are logged to the console! Awesome. I now have the URLs i needed! The issue I'm having is, it will only let me push these values to a local array. In this instance 'var array'. I need to push to an array that's outside of the 'activatedRoute' 'method'. Anytime I do, it returns as undefined.
this.activatedRoute.data
.subscribe((
data: { issueData: any, issueImageData: any }) => {
this.issueToDisplay = data.issueData;
this.imagesToDisplay = data.issueImageData;
var array = [];
data.issueImageData.forEach(image => {
// Reference to the image URL
var image = image.url;
// Firebase storage
var storage = firebase.storage();
// Path reference
var imagePathReference = storage.ref().child(image);
// Get Download URL
imagePathReference.getDownloadURL().then(function (url) {
console.log(url);
array.push(url);
})
});
});
I would recommend you to use the features rxjs provides you:
this.activatedRoute.data.switchMap(data => {
let parsedData = {
issueToDisplay: data.issueData,
imagesToDisplay: data.issueImageData
}
let imageUrls$ = data.issueImageData.map(image => {
var imagePathReference = storage.ref().child(image);
return Observable.fromPromise(imagePathReference.getDownloadURL())
});
return Observable.forkJoin(imageUrls$).map((...urls) => {
return Object.assign(parsedData, { urls });
})
}).subscribe(data => {
/*
data looks like this:
{
issueToDisplay: any,
imagesToDisplay: any,
urls: string[]
}
*/
});
If I'm correct, you're looking for a solution to map an array-like object of objects to an actual array of objects.
Here is a way to do just that:
var object = {
'0': {
"url": "url1",
"name": "obj1",
"data": 1234
},
'1': {
"url": "url2",
"name": "obj2",
"data": 5678
},
'length': 2
}
var sliced = Array.prototype.slice.call( object, 0 );
console.log(sliced)
Couple remarks:
If you wonder how this works, check this post.
Alternative syntax that you could encounter looks like [].slice.call()
If you want to perform array-like operations, you can probably do that right away with Array.prototype.<METHOD>.call(object, <CALLBACK>
For example:
Array.prototype.map.call(object, function(el) { // return your enhanced element })
So, this works. Not entirely sure how clean it is. But it works.
this.activatedRoute.data
.subscribe((
data: { issueData: any, issueImageData: any }) => {
this.issueToDisplay = data.issueData;
this.imagesToDisplay = data.issueImageData;
var localImageArray = [];
data.issueImageData.forEach(image => {
// Reference to the image URL
var image = image.url;
// Firebase storage
var storage = firebase.storage();
// Path reference
var imagePathReference = storage.ref().child(image);
// Get Download URL
imagePathReference.getDownloadURL().then(function (url) {
localImageArray.push(url);
})
this.getIssueImageArray(localImageArray);
});
});
}
// Get Image Array
getIssueImageArray(array) {
this.imageToDisplayArray = array;
}
I need to fetch several documents from my db, each one has an attachment, how can I get every document and assign its attachment dynamically and display a list using AngularJS?
Here's the bit of code I'm using:
db.getAttachment(doc._id,"image.png").then(function (blob){
var url = URL.createObjectURL(blob);
$scope.image = url;
});
How can "image.png" be a dynamic id? So I can iterate on it with a for loop
Thanks!
You could use the _attachments field and do something like:
for(var key in doc._attachments){
db.getAttachment(doc._id,key).then(function (blob){
var url = URL.createObjectURL(blob);
$scope.image = url;
});
}