首页 \ 问答 \ Spring Boot 2 Reactor Flux API的Angular客户端(Angular client of Spring Boot 2 Reactor Flux API)

Spring Boot 2 Reactor Flux API的Angular客户端(Angular client of Spring Boot 2 Reactor Flux API)

如何为Java Project Reactor反应性Flux API创建Angular 4客户端? 下面的示例有两个API: Mono API; 和, Flux API。 两者都是curl ; 但在Angular 4(4.1.2)中,只有Mono API有效; 任何想法如何让Angular 4与Flux API一起使用?

这是一个简单的Spring Boot 2.0.0-SNAPSHOT应用程序,带有Mono API和Flux API:

@SpringBootApplication
@RestController
public class ReactiveServiceApplication {

    @CrossOrigin
    @GetMapping("/events/{id}")
    public Mono<Event> eventById(@PathVariable long id) {
        return Mono.just(new Event(id, LocalDate.now()));
    }

    @CrossOrigin
    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Event> events() {
        Flux<Event> eventFlux = Flux.fromStream(
            Stream.generate(
                ()->new Event(System.currentTimeMillis(), LocalDate.now()))
            );

        Flux<Long> durationFlux = Flux.interval(Duration.ofSeconds(1));

        return Flux.zip(eventFlux, durationFlux).map(Tuple2::getT1);
    }

    public static void main(String[] args) {
        SpringApplication.run(ReactiveServiceApplication.class);
    }
}

使用Lombok编辑的活动:

@Data
@AllArgsConstructor
public class Event {
    private final long id;
    private final LocalDate when;
}

正如我所期望的那样,这些反应性API在curl中起作用:

jan@linux-6o1s:~/src> curl -s http://localhost:8080/events/123
{"id":123,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

类似地,对于非终止的Flux API:

jan@linux-6o1s:~/src> curl -s http://localhost:8080/events
data:{"id":1494887783347,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

data:{"id":1494887784348,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

data:{"id":1494887785347,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

...

使用RxJS的同样微不足道的Angular 4客户端:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements OnInit, OnDestroy {
  title = 'app works!';
  event: Observable<Event>;
  subscription: Subscription;

  constructor(
    private _http: Http
    ) {
  }

  ngOnInit() {
    this.subscription = this._http
      .get("http://localhost:8080/events/322")
      .map(response => response.json())
      .subscribe(
        e => { 
          this.event = e;
        }
      );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

适用于Mono API:

"http://localhost:8080/events/322"

但是Flux API:

"http://localhost:8080/events"

永远不会触发事件处理程序,与curl不同。


How do I create an Angular 4 client for a Java Project Reactor reactive Flux API? The sample below has two APIs: a Mono API; and, Flux API. Both work from curl; but in Angular 4 (4.1.2) only the Mono API works; any ideas how to get Angular 4 to work with the Flux API?

Here's a trivial Spring Boot 2.0.0-SNAPSHOT application with a Mono API and a Flux API:

@SpringBootApplication
@RestController
public class ReactiveServiceApplication {

    @CrossOrigin
    @GetMapping("/events/{id}")
    public Mono<Event> eventById(@PathVariable long id) {
        return Mono.just(new Event(id, LocalDate.now()));
    }

    @CrossOrigin
    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Event> events() {
        Flux<Event> eventFlux = Flux.fromStream(
            Stream.generate(
                ()->new Event(System.currentTimeMillis(), LocalDate.now()))
            );

        Flux<Long> durationFlux = Flux.interval(Duration.ofSeconds(1));

        return Flux.zip(eventFlux, durationFlux).map(Tuple2::getT1);
    }

    public static void main(String[] args) {
        SpringApplication.run(ReactiveServiceApplication.class);
    }
}

with a Lombok-ed event:

@Data
@AllArgsConstructor
public class Event {
    private final long id;
    private final LocalDate when;
}

These reactive APIs work from curl as I'd expect:

jan@linux-6o1s:~/src> curl -s http://localhost:8080/events/123
{"id":123,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

and similarly for the non-terminating Flux API:

jan@linux-6o1s:~/src> curl -s http://localhost:8080/events
data:{"id":1494887783347,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

data:{"id":1494887784348,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

data:{"id":1494887785347,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}

...

The similarly trivial Angular 4 client with RxJS:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements OnInit, OnDestroy {
  title = 'app works!';
  event: Observable<Event>;
  subscription: Subscription;

  constructor(
    private _http: Http
    ) {
  }

  ngOnInit() {
    this.subscription = this._http
      .get("http://localhost:8080/events/322")
      .map(response => response.json())
      .subscribe(
        e => { 
          this.event = e;
        }
      );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

works fine for the Mono API:

"http://localhost:8080/events/322"

but the Flux API:

"http://localhost:8080/events"

never triggers the event handler, unlike curl.


原文:https://stackoverflow.com/questions/43989889
更新时间:2022-04-22 15:04

最满意答案

编辑:试试这个:

var show = false;
if (locationsFilter) {
  if (jQuery.inArray(tempLocation, locationsFilter) != -1) {
    show = true;
  }
}
if (!show && departmentsFilter) {
  if (jQuery.inArray(tempDepartment, departmentsFilter) != -1) {
    show = true;
  }
}
if (!show && titlesFilter) {
  if (jQuery.inArray(tempTitle, titlesFilter) != -1) {
    show = true;
  }
}
if (show) $(this).show();

查看编辑过的小提琴: https//jsfiddle.net/p4xvgLo1/7/


EDITED: Try with this:

var show = false;
if (locationsFilter) {
  if (jQuery.inArray(tempLocation, locationsFilter) != -1) {
    show = true;
  }
}
if (!show && departmentsFilter) {
  if (jQuery.inArray(tempDepartment, departmentsFilter) != -1) {
    show = true;
  }
}
if (!show && titlesFilter) {
  if (jQuery.inArray(tempTitle, titlesFilter) != -1) {
    show = true;
  }
}
if (show) $(this).show();

See the edited fiddle: https://jsfiddle.net/p4xvgLo1/7/

相关问答

更多
  • 看看这个jsfiddle 。 这个想法是用函数来过滤行,这些函数将循环遍历单词。 jo.filter(function (i, v) { var $t = $(this); for (var d = 0; d < data.length; ++d) { if ($t.is(":contains('" + data[d] + "')")) { return true; } } return false; }) //show ...
  • uiTableFilter插件不支持你想要做的事情。 快速查看源代码可以发现: elems.each(function(){ var elem = jQuery(this); jQuery.uiTableFilter.has_words(getText(elem), words, false) ? matches(elem) : noMatch(elem); }); 并且扩展到(基本上)这个: elems.each(function(){ var e ...
  • 过滤匹配行的一个选项是创建过滤条件数组。 这允许您灵活地过滤匹配的行。 首先,我将使用data-*属性将目标单元格的索引添加到按钮或按钮的父元素。
    ...
    在上面的代码片段中, data-cell-index指定目标单元格 ...
  • 编辑:试试这个: var show = false; if (locationsFilter) { if (jQuery.inArray(tempLocation, locationsFilter) != -1) { show = true; } } if (!show && departmentsFilter) { if (jQuery.inArray(tempDepartment, departmentsFilter) != -1) { show = true; } } ...
  • 一种选择是将过滤器存储在一个数组中: http : //jsfiddle.net/4yWWH/ 编辑:修改为显示所有产品,如果没有过滤器则退出: http : //jsfiddle.net/4yWWH/1/ One option would be to store the filters in an array: http://jsfiddle.net/4yWWH/ EDIT: modified to show all products and exit if there are no filters: h ...
  • 您只需要检查输入值是否为空: $('#filterText').html($(this).val() ? 'and Filter = "' + $('#filter').val()+'"' : ''); 的jsfiddle You just need to check whether the input value is empty or not: $('#filterText').html($(this).val() ? 'and Filter = "' + $('#filter').val()+'"' ...
  • 如果您还想匹配类名片段(例如,在键入“ple”时显示“apple”),请考虑使用属性包含选择器'[class*="'+filter+'"]' 。 结合上面的答案: function filter() { var filter = $("#filter").val(); var photos = $('.photo'); photos.show(); if (filter != '') photos.not('[class*="'+filter+'"]').hide(); ...
  • 这可以通过将事件延迟大约10毫秒来实现,用户不会注意到差异,但它会帮助您。 我为你的问题做了一个小提琴 。 这是它基本上做的: $(function () { var input = $("#entry"); input.keydown(function () { // doesn't matter if you create an anonymous method or a regular method, only the setTimeout is of value ...
  • 要解决此问题,请在代码中添加以下行。 $rows.show(); 在应用过滤器选项之前添加此代码。 您可以在此块之后添加。 inputContent = $input.val().toLowerCase(), $panel = $input.parents('.filterable'), column = $panel.find('.filters th').index($input.parents('th')), $table = $panel.find('.table'), $rows = $tabl ...
  • 这里的重要性是理解jQuery的$(this)和普通的旧javascript event.target之间的区别。 考虑这个例子 。 大蓝框是我们的按钮,它包含了里面的所有红色框。 请注意,当您将鼠标悬停在它们上方时: $(this)始终引用与事件绑定的元素。 因为我们的事件与按钮点击有关,所以$(this)总是引用按钮 。 另一方面, event.target在很多情况下几乎过于具体 。 当您将鼠标悬停在红色框上时,您会注意到event.target指的是正在悬停的确切元素 。 通过执行event.tar ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)