Search code examples
angularloopbackjsloopbackangular-loopback

how do I add an image to a loopback model?


I created a blog post using mongodb(mlab), loopback, and angular 4 and I am able to display my posts on my angular 4 site, however I do not know how to add an image to my loopback model seen here as json:
{ "title": "string", "author": "string", "date": "string",// type could be date "body": "string", "id": "string" }

There is no image property type so I am confused as to how to add my image url to my loopback data model in order to display it on my angular 4 blog. I could use <img *ngIf="post.id === '599ce3147e0f7a32c812a6ac'" src="http://drvidyahattangadi.com/wp-content/uploads/2014/12/panchkarma3.jpg" alt=""> for each post id but if I have many posts this would be wildly inefficient. Can anyone help?


Solution

  • When you working with Image type of objects in Loopback recommended approach is that create component storage to your loopback application.

    npm install loopback-component-storage --save
    

    You just need to provide series of answers like in following code in CLI.

    $ slc loopback:datasource
    [?] Enter the data-source name: storage
    [?] Select the connector for storage: other
    [?] Enter the connector name without the loopback-connector- prefix: loopback-component-storage
    [?] Install storage (Y/n)
    

    in the datasource.json file your storage entry will added.

    "storage": {
      "name": "storage",
      "connector": "loopback-component-storage",
      "provider": "filesystem",
      "root": "./files"
    }
    

    After creating required "model" you can simply work with file struture to download and upload images.

    ex:
    POST /api/containers/container-name/upload
    

    Following link will help you with step by step process to create component storage and image upload/download functionalities in loopback.