动态og:图像angular2

时间:2017-01-04 01:44:54

标签: angular facebook-opengraph opengraph

我们希望在社交网络上分享指向Angular 2的网址。例如Facebook和Skype。

在我们的网站上,此网址会根据我们设置的实际网址参数和查询字符串显示动态图片。

例如,转到http://oursite.com/#/show/5448sd84f8d4sf8会显示/images/5448sd84f8d4sf8.png

通过共享链接,似乎Facebook和Skype都使用Open Graph meta og:image来显示网站的缩略图或快照:

<meta name="og:image" content="http://example.com/image.png">

有没有办法根据网址设置动态og:图片,如下所示:链接我们的网址会显示

<meta name="og:image" content="http://oursite.com/images/5448sd84f8d4sf8.png">

然后如何确保Facebook和Skype能够实际解析动态图像?

3 个答案:

答案 0 :(得分:2)

您可以使用Angular的import { Title, Meta } from '@angular/platform-browser'; export class MyClass { constructor( private metaService: Meta ) { // Build and change the og:image meta const baseUrl = window.location.protocol + '//' + window.location.hostname; const imageUrl = baseUrl + '/path/to/image.png'; this.metaService.addTag( { property: 'og:image', content: imageUrl } ); // or it it already exists, use this 'updateTag' // this.metaService.updateTag( { property: 'og:image', content: imageUrl } ); } } 服务来修改元标记:

@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public String greeting(@RequestParam("file") MultipartFile file) {
    try {
        byte[] bytes = file.getBytes();

        //to save file, if it is your case
        Path path = Paths.get("/" + file.getOriginalFilename());
        Files.write(path, bytes);

    } catch (IOException e) {
        e.printStackTrace();
    }

}

答案 1 :(得分:0)

我也遇到了同样的问题。  Angular 2浏览器应用程序在客户端运行。要解决此问题,我们需要处理此表单服务器端,当请求来自客户端时。 (使用og meta标签的简单更新响应)

有几种选择:

  • 选择Angular Universal:有点困难的方法

  • 通过URL重写(Web服务器)简单处理这个:这就是我使用的

这是我为url重写的web配置:我从查询参数(.. go = [filename])中获取动态og图像名称

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

app.directive('numbersOnly', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {


        if (parseInt(inputValue) <= 100 && parseInt(inputValue) > 0) {
          modelCtrl.$setValidity('numbersOnly', true);
          return inputValue;
        } else {
          modelCtrl.$setValidity('numbersOnly', false);
          return modelCtrl.$modelValue;
        }

      });
    }
  };
});

function MyCtrl($scope) {
  $scope.number = ''
}

答案 2 :(得分:-3)

您可以使用ng2-metadata,它很容易实现。

https://www.npmjs.com/package/ng2-metadata

相关问题