标签: angular5

如何通过角度行为主体传递多个(2个或多个)变量

我是 rxjs 新手。在我的应用程序中,我遇到了一种将用户名和密码值从一个组件传递到另一个组件的情况(以角度方式)。请您帮助我通过行为主题将这些变量从一个组件传递到另一个组件,并提供一个简洁的基本示例。我有一个类存储用户详细信息 UserInformation.ts 如下

export class UserInformation {
    username: string;
    constructor() {
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个服务如下。用户信息.service.ts

import { Injectable } from '@angular/core';
import { UserInformation } from '../UserInformation';
@Injectable()
export class UserInformationService {
  userData:UserInformation;
  variable:string='ServiceVariable';
  constructor() {
    this.userData = new UserInformation(); 
   }
  getUserData()
  {
    return this.userData;
  }
  setUserData(userData:UserInformation)
  {
    this.userData.username=userData.username;
    console.log(this.userData.officeLocation);
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的 FirstComponent.ts 中,我有以下代码。这个 getVALuesFromForm 方法用于从表单中获取用户名。

getValuesFromForm()
   {
     this.enteredUser.username = this.loginform.get('Username').value;
     console.log(this.enteredUser.username);
     this.service.setUserData(this.enteredUser);     
   }
Run Code Online (Sandbox Code Playgroud)

在我的 secondaryComponent.ts 中,我有以下代码。

import { Component, OnInit , Input , Output  } from '@angular/core'; …
Run Code Online (Sandbox Code Playgroud)

rxjs angular angular5

3
推荐指数
1
解决办法
9800
查看次数

HttpInterceptor 上的递归太多

在我的应用程序中,身份验证基于 JWT 令牌。为了使它们无效,我在 JWT 中放置了一个随机安全字符串,并在数据库中放置了与拥有令牌的用户相关联的完全相同的字符串。这两个必须匹配才能使 JWT 有效。当用户注销时,API 会生成另一个随机字符串并替换数据库中的旧字符串,从而使 JWT 对该用户无效,因为 de JWT 中的字符串与数据库的字符串不匹配。

为此,我需要一个拦截器,在对 API 的每个请求之前发出一个静默请求,以检查随机字符串是否相等。基于这个问题,我的拦截器工作但行为怪异,发出无限请求并抛出“递归过多”错误。

我究竟做错了什么?

拦截器

 import { TokenService }     from './token.service';
 import { Router }           from '@angular/router';
 import { HttpInterceptor,
     HttpRequest, 
     HttpHandler, 
     HttpEvent, 
     HttpClient,
     HttpHeaders }       from "@angular/common/http";
 import { Injectable }       from "@angular/core";
 import { Observable }       from "rxjs/Observable";
 import { SharedService }    from "./shared-service.service";
 import { CookieService }    from 'ngx-cookie-service';

 @Injectable()

export class AuthInterceptor implements HttpInterceptor {


constructor(private sharedService : SharedService,
            private httpClient …
Run Code Online (Sandbox Code Playgroud)

interceptor typescript angular5

3
推荐指数
1
解决办法
553
查看次数

Firebase 网络推送通知

我正在尝试使用 angular5 和 Codeignitor 中的 firebase 发送网络推送通知。初始化 firebase 后,我可以将 deviceToken 发送给我想要发送推送通知的人。当我尝试使用 curl 在后端发送它时。它总是向我显示这个错误

{
    "multicast_id":8778443463170192739,
    "success":0,
    "failure":1,
    "canonical_ids":0,
    "results":[
        {
            "error":"MismatchSenderId"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

在后端 api 请求中,我使用的是“服务器密钥” "AAAA8q7RESs:APA91bFrOrzgvTb0yQTqTF6huozIvgi_5xf1lY8qv5kyoDViuBYnVFr3Qfxg3DZHN_e7-AqWBIvRlQvPJkgZtxKIpCYs_aUUiYHOKuKLLJvzxAENjKmF4mCQJb94tJV8J-vBgnv0FPPY".

但总是显示相同的错误。

我的后端 PHP 代码是

public function sendpushnotification() {
    $request = json_decode(file_get_contents('php://input'),true);
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array(
        'registration_ids'  => array($request['token']),
        'data'              => array( "message" => "Hello this is test push notification" ),
    );
    $headers = array( 
        'Authorization: key=AAAA8q7RESs:APA91bFrOrzgvTb0yQTqTF6huozIvgi_5xf1lY8qv5kyoDViuBYnVFr3Qfxg3DZHN_e7-AqWBIvRlQvPJkgZtxKIpCYs_aUUiYHOKuKLLJvzxAENjKmF4mCQJb94tJV8J-vBgnv0FPPY',
        'Content-Type: application/json'
    );


    // Open connection
    $ch = curl_init();

    // Set the url, number …
Run Code Online (Sandbox Code Playgroud)

codeigniter push-notification firebase firebase-cloud-messaging angular5

3
推荐指数
1
解决办法
3026
查看次数

Angular 5 ngSubmit @Output 触发两次

定制组件

// ...

@Output() submit: EventEmitter < any > = new EventEmitter();

// ...

onFilterSubmit($event): void {
  this.submit.emit($event);
  this.formData = {
    minDate: new Date().toISOString(),
    maxDate: new Date().toISOString()
  };
}
Run Code Online (Sandbox Code Playgroud)
<form (ngSubmit)="onFilterSubmit(formData)">

    <!-- -- -->
    <button mat-button
        mat-raised-button
        [disabled]="reqsForm.form.invalid" 
        type="submit"
        color="primary">
        {{labels.submit}}
    </button>
</form>
Run Code Online (Sandbox Code Playgroud)

外部组件

// ...

onFilterSubmit($event): void {
  console.info("FORM SUBMIT", $event);
}
Run Code Online (Sandbox Code Playgroud)
<custom-component (submit)="onFilterSubmit($event)">

  <!-- -- -->

</custom-component>
Run Code Online (Sandbox Code Playgroud)

输出

FORM SUBMIT > Object

FORM SUBMIT > Object

events components output angular5

3
推荐指数
1
解决办法
1174
查看次数

如何在 angular 6 中加载自定义字体?

我目前在 angular 6 中工作。我想在 style.css 中加载我的字体,但它不起作用。我的代码如下所示。有人可以建议我如何重现这个问题吗?

注意:我使用了在 angular 5 中使用的相同语法。它有什么问题?

样式.css:

@font-face {
  font-family: 'Expert Sans';
  src: url('assets/fonts/ExpertSans-Regular.ttf');
}


body {
  font-family: 'Expert Sans' !important;
  font-size: 14px;
  line-height: 1.42857143;
  color: #333;
  background-color: #fff;
  margin: 0;
}
Run Code Online (Sandbox Code Playgroud)

javascript typescript angular5 angular6

3
推荐指数
1
解决办法
7330
查看次数

Mean Stack:刷新或输入直接 URL 会导致“无法获取/”?

我使用 MEAN 堆栈创建了一个网页。角 5。

我遇到的一个问题是我无法输入直接 url 路径。例如,如果我最后输入 /home,则会收到此错误消息“无法获取 /home”。当我点击刷新时也会发生这种情况。该页面完美运行如果我点击主页上的“主页”导航按钮。

例如:这是我的页面:https : //nameless-hollows-54410.herokuapp.com/

当我转到直接链接时,https://nameless-hollows-54410.herokuapp.com/home

页面坏了。为什么会这样?

我的应用程序路由代码:

const routes: Routes  = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent},
];
Run Code Online (Sandbox Code Playgroud)

我的导航栏:

<li class="nav-item active">
   <a class="nav-link" routerLink="/home">Home
       <span class="sr-only">(current)</span>
   </a>
</li>
Run Code Online (Sandbox Code Playgroud)

heroku node.js angular angular5

3
推荐指数
1
解决办法
781
查看次数

'Observable&lt;Object&gt;' 类型不存在属性 'timeout'

我正在尝试从 5 升级到 Angular 6 并收到此错误:

src/app/services/http.service.ts(17,14) 中的错误:错误 TS2339:“可观察”类型上不存在属性“超时”。

我在 http.service.ts 中的代码:

import { throwError as observableThrowError,  Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { environment } from "environments/environment";
import { AppService } from 'app/app.service';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class HttpService {

    private baseUrl = environment.apiUrl;

    constructor(private http: HttpClient, private appService: AppService) { }

    public get(endpoint: string): Observable<any>{
        return this.http.get(this.baseUrl + endpoint)
            .timeout(this.appService.timeoutInterval)
            .retryWhen(error => error.delay(this.appService.waitInterval)
                .take(this.appService.numberOfRetries)
                .concat(observableThrowError(new Error())))
            .share();
    }
} …
Run Code Online (Sandbox Code Playgroud)

rxjs5 angular angular5 angular6 rxjs6

3
推荐指数
1
解决办法
5983
查看次数

ErrorHandler:与 promise 一起使用时无法获取错误对象

我正在构建一个实现自定义错误处理程序的角度应用程序。

当你有一个自定义的错误处理程序并且当一个 observable 与 http 一起使用并且当错误没有被捕获时,使用一个 catch 块,如下所示

this.http.get('/doesntExist').subscribe();
Run Code Online (Sandbox Code Playgroud)

自定义 ErrorHandler 的 handleError() 函数获取一个 HttpErrorResponse 对象,该对象可用于获取必要的信息并全局处理错误。但是当你使用承诺时,就像下面这样

this.http.get('/doesntExist').toPromise();
Run Code Online (Sandbox Code Playgroud)

而不是 HttpErrorResponse ,将抛出一个字符串说

错误:未捕获(承诺):HttpErrorResponse:

并且您无法在 handleError() 方法中真正获得错误信息。你可以在这里看到它的实际效果

这是理想的行为吗?难道我做错了什么?有什么解决方法吗?请帮忙。我被卡住了;

更新

控制台中字符串错误的堆栈跟踪

Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":[],"lazyUpdate":null},"status":200,"statusText":"OK","url":"https://angular-promise-bug.stackblitz.io/doesntExist","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for https://angular-promise-bug.stackblitz.io/doesntExist","error":{"error":{},"text":"<!DOCTYPE html>\n<html>\n<head>\n  <link href=\"https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700|Lato:400,700,900\" rel=\"stylesheet\">\n  <base href=\"/\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" />\n  <link rel=\"stylesheet\" media=\"screen\" href=\"https://c.staticblitz.com/assets/preview-8222014a50f8588c56d057621cdaf871.css\" />\n  <script src=\"https://c.staticblitz.com/assets/common-bd7eff1ca58185bf8131b.js\" crossorigin=\"anonymous\"></script>\n  <script src=\"https://c.staticblitz.com/assets/ext-fb68da629568861fd08cb.js\" crossorigin=\"anonymous\"></script>\n  <script src=\"https://c.staticblitz.com/d/webcontainer.a966dcc4085d3fff5bb.js\" crossorigin=\"anonymous\"></script>\n  <script src=\"https://c.staticblitz.com/assets/preview-3a0c9433aa42f56dbd90b.js\" crossorigin=\"anonymous\"></script>\n  <script>(function(){_preboot(\"https://l.staticblitz.com/b/v1/angular-promise-bug/f9f42b37e9b\",{p:\"stackblitz\",a:\"AIzaSyBZSvuCzbUhuRrSps-HjM5bFClLPaFF9Vg\",o:true})})()</script>\n</head>\n<body></body>\n</html>\n"}}
    at resolvePromise (angular-promise-bug.stackblitz.io/turbo_modules/zone.js@0.8.26/dist/zone.js:814)
    at eval (angular-promise-bug.stackblitz.io/turbo_modules/zone.js@0.8.26/dist/zone.js:724)
    at SafeSubscriber.eval [as …
Run Code Online (Sandbox Code Playgroud)

angular angular5

3
推荐指数
1
解决办法
5048
查看次数

安全管道中的 Angular 5 出现错误 - 需要一个安全的 ResourceURL,得到一个 HTML

在 Angular 5 中,我想在iFrame. 我使用了安全管道,但是在控制台中收到错误

需要一个安全的 ResourceURL,得到一个 HTML

这是代码是我的.ts文件:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

export class XXXComponent implements OnInit {
constructor(private sanitizer: DomSanitizer){}

this.mapURL = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDdWRYxwcpnrJWXbsR4fmP3HwvsFlCMYPk&q=Ylistörmä+1,+02210+Espoo,+Finland&attribution_source=Google+Maps+Embed+API";
this.urlsafe = this.createSafeMap(this.mapURL);

createSafeMap(url){
   return this.sanitizer.bypassSecurityTrustHtml(url);
}
Run Code Online (Sandbox Code Playgroud)

在.html文件中,我执行以下操作以在 iframe 中显示地图:

<iframe [src]="urlsafe | safe: 'html'"></iframe>
Run Code Online (Sandbox Code Playgroud)

以下是内容safe.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
    
@Pipe({
   name: 'safe'
})
export …
Run Code Online (Sandbox Code Playgroud)

angular angular5

3
推荐指数
1
解决办法
3915
查看次数

错误 TS2678 类型“'String'”与 Angular 5 中的类型 '""' 不具有可比性

这是我的角度 5 代码:

gotToWallet(wallet) {

  const { countryId = '', currencyType = '' } = wallet || {};

  let walletIdentity;

  switch (currencyType) {
    case 'CRYPTO':
      walletIdentity = 'userWalletIdentity';
     break;
    case 'FIAT':
      walletIdentity = 'fiatWalletIdentity';
     break;
    case 'ERC20TOKEN':
      walletIdentity = 'xbxUserWalletIdentity';
     break;
 }

  const { currencyId = '' } = (wallet || {})[walletIdentity] || {};
  this.router.navigate([`walletMgmt/wallet-details/${currencyId}/${countryId}`]);

}
Run Code Online (Sandbox Code Playgroud)

运行ng build命令时出现以下错误:

ERROR in src/app/wallet-management/wallets/wallets.component.ts(202,12): error TS2678: Type '"CRYPTO"' is not comparable to type '""'.
src/app/wallet-management/wallets/wallets.component.ts(205,12): error TS2678: Type '"FIAT"' is not …
Run Code Online (Sandbox Code Playgroud)

javascript switch-statement typescript angular5

3
推荐指数
1
解决办法
6737
查看次数